/*
$Rev:: 516           $:  Revision of last commit
$Author:: geopat     $:  Author of last commit
$Date:: 2009-06-03 1#$:  Date of last commit
*/

//Global Variables
var flashCrop = false;
var checkSiFR = false;
var globalAssetsPath = "/images/";
var careersXMLFilePath = "/so/xml/";
var careersCSSFilePath = "/so/css/";
var imageSoPath = globalAssetsPath + "so_";
var videoSplashPostfix = "_splash"
var hasFlashContent = false;
var viewNonFlashVersion = "ดูในเวอร์ชันไม่ใช้แฟลช";

/*hide flash fallback version of homepage before DOM inserts flash*/
document.write ("<style type=\"text/css\">div#homepage-no-flash-version{visibility: hidden;}</style>");

// prevent bg flicker bug in IE6
/*@cc_on @*/
/*@if (@_win32)
try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {}  
/*@end @*/


// Updated by Unilever
document.write ("<style type=\"text/css\">div.selectbox input.submit{display: none;}</style>");
// End of Unilever update

// On DOM ready functions
$(document).ready(function() {
	setupStylesSwitch();		// For development purposes only, expedient method to switch between & demonstrate page styles
	testFonts();
	setupIeHover();
	setupPageResizing();
	setupOverviewList();
	setupEqualHeightList();
	setupAdvSearch();
	setupUnileverWorldWide();
	setupPrimaryNavigation();
	setupSecondaryNavigation();
	setupCareersFunctionality();
	setupSearchFunctionality();
	setupMapInHeader();
	setupPageSelector();
	setupFlashCropper();
	formHighlighter();
	if ($('body.stylesOurBrands').length > 0) {
		unilever.brandTopic.init();
	}
	if ($('body.stylesHomePage').length > 0) {
		unilever.homeTopic.init();
	}
	if (typeof maxTopics != 'undefined') {
		unilever.ajaxTopic.init();
	}
});

function testFonts() {
	if ((checkSiFR) && (!document.getElementById("DisableSiFR"))) { 
		replaceFonts(); 
	}
}

// Extracts variable on the URL, sets this as a class on the body. Not intended for live site, just to demonstrate the effects of different body classes
function setupStylesSwitch() {
	var urlVariable = "class="
	var url = document.location.href;
	var urlPosition = url.indexOf(urlVariable);
	var urlRemainder = url.slice(urlPosition)
	var urlAfterVariable = urlRemainder.substring(urlVariable.length)
	if (urlAfterVariable != "") {
		$('body')[0].className = "lowerPage";
		$('body').addClass(urlAfterVariable);
	}
}



// Add min-max page width functionality for IE6
function setupPageResizing() {
    // Resize the page for IE6
	checkSize();

	// Attach resize functionality for IE6 on window's resize event
	var resizeTimeoutId;    //timer is needed to get around IE6 firing multiple resize events on window.resize
	$(window).resize(function(){
		window.clearTimeout(resizeTimeoutId);
		resizeTimeoutId = window.setTimeout(function(){
			checkSize();
		}, 10);
	});
}



function setupIeHover(){
	ieHover('body.stylesCareersHubPage div.section');
	ieHover('body.stylesCareers div.cModule h3');
	ieHover('div.heroPanelContentSmall');
	ieHover('#primaryNav li');
	ieHover('ul#footerBreadcrumb li');
	ieHover('ul.unileverWorldWideStoryList li');
	ieHover('body.stylesCareers div.multimediaBox p.nextTab a');
	ieHover('body.stylesCareers a.videoImage span.videoImageOverlay');
	ieHover('input.submit');
}



// Inserts 'ieHover' class for use in IE6
function ieHover(e) {
  $(e).hover(
    function () {
		if ($(this).hasClass("selected")) {
			$(this).addClass('ieHoverSelected');
		} else if ($(this).hasClass("submit")) {
			$(this).addClass('submitIeHover');
		} else if ($(this).hasClass("unileverWorldWideRightAlign")) {
			$(this).addClass('unileverWorldWideRightAlignIeHover');
		}
		$(this).addClass('ieHover');
	},
    function () {
		$(this).removeClass('ieHover');
		$(this).removeClass('ieHoverSelected');
		$(this).removeClass('submitIeHover');
		$(this).removeClass('unileverWorldWideRightAlignIeHover');
	}
  );
}




// Applies classes for different page widths to get around IE6's lack of support for min & max width
function checkSize() {
	if ($(window).width()<=775) {
		removeClasses();
		$('html').addClass('windowMinWidth');
	} 
	else if (($(window).width()>775)&&($(window).width()<920)) {
		removeClasses();
		$('html').addClass('windowCollapseWidth');	 // used on homepage to collapse small panels
		$('html').addClass('windowMidWidth');
	}
	//else if ($(window).width()>1010) {
	else if ($(window).width()>920) {
		removeClasses();
		$('html').addClass('windowMaxWidth');
	} 
	else {
		removeClasses();
		$('html').addClass('windowMidWidth');
	}
	function removeClasses() {
		$('html').removeClass('windowMinWidth');
		$('html').removeClass('windowMidWidth');
		$('html').removeClass('windowMaxWidth');
		$('html').removeClass('windowCollapseWidth');
	}
}



function drawNav(l) {
  $('#secondaryNav li').hide();
  l.parents('ul').setLevel('l1');
  l.parents('ul:first').setLevel('l2');
  l.siblings('ul').setLevel('l3');
  $('#secondaryNav .l3 ul').hide();
  l.parents('li').show();
  l.parent('li').siblings('li').show();
  l.siblings('ul').show();
  l.siblings('ul').children('li').show();
  $('#secondaryNav li a.divider').removeClass('divider');
  l.parents('ul:first').parent('li').children('a:first').addClass('divider');
}

jQuery.fn.extend({
  setLevel: function(l) {
	if ($(this).hasClass('l1')) $(this).removeClass('l1');
	if ($(this).hasClass('l2')) $(this).removeClass('l2');
	if ($(this).hasClass('l3')) $(this).removeClass('l3');
	$(this).addClass(l);
  }
});




function setupCareersFunctionality() {

	//Setup flash content for Careers
	if (typeof hasFlashContent != 'undefined') {
		setupFlashOnHomePage();
	}
	setupVideoPlayers();



	//Collapsible Modules
	$('div.cHide div.content').hide();
	$('div.cModule').addClass('collapsingContent');
	$('div.cModule div.summary > h3').click( function () {
		$(this).parent('div.summary').siblings("div.content").toggle();
		$(this).parents('div.cModule').toggleClass('cHide');
	});



	//Landing page section links
	$('div.landing div.section').hover(
		function () {
		  if (!$(this).children('p').hasClass('links')){$(this).addClass('linkHover');}},
		function () {
		  if (!$(this).children('p').hasClass('links')){$(this).removeClass('linkHover');}
		}
	);

	$('div.landing div.section a.highlight').hover( function () {
		if ($(this).parent('div.section').children('p').hasClass('links')){
		  $(this).parent('div.section').addClass('hoverOverride');
		}
		}, function () {
		if ($(this).parent('div.section').children('p').hasClass('links')){
		  $(this).parent('div.section').removeClass('hoverOverride');
		}
	});

	$('div.landing div.section').click( function () {
		if ($(this).children('p').hasClass('links')) { location.href = $(this).children('p.links').children('a').attr('href'); }
		else { location.href = $(this).children('a.highlight').attr('href'); }
	});




	//Slideshow
	$('ul.slideshow li.slide').hide();
	$('ul.slideshow li#slide1').show();
	$('ul.slideshow li#slide_p1_1').show();
	$('ul.slideshow li#slide_p2_1').show();
	$('ul.slideshow li#slide_p3_1').show();

	$('ul.slideshow div.slideshowNavigation a.slideshowNavigationPrevious').click( function () {
		$(this).parents('li.slide').hide();
		$(this).parents('li.slide').prev().show();
		return false;
	});

	$('ul.slideshow div.slideshowNavigation a.slideshowNavigationNext').click( function () {
		$(this).parents('li.slide').hide();
		$(this).parents('li.slide').next().show();
		return false;
	});



	// Style Enhancements

	// Updated by Unilever
	$('div.selectbox input.submit').hide();
	$('div.filter div.selectbox select').change(function() {
		$(this)[0].form.submit();
	});
	// End of Unilever update



	$('#header div.country .submit').hide();
	$('#footerLinks div.linksGroup').hover(
		function () { $(this).children('h5').css('color','#37BEEB'); },
		function () { $(this).children('h5').css('color','#999'); }
	);




	//Carousel width
	$('div.videoCarousel ul.thumbnails').css('width',$('div.videoCarousel ul.thumbnails').children().size()*165+'px');




	//Location
	$('div.mapContainer a.expand').click( function () {
		$(this).parents('div.mapContainer').removeClass('compact');
		return false;
	});
	$('div.mapContainer a.collapse').click( function () {
		$(this).parents('div.mapContainer').addClass('compact');
		return false;
	});




	// Profile Tabs on Careers
	$("#profile ul.tabs").tabs();
	$("#profile p.nextTab a").click( function () {

		var newTab = $(this).attr('href');

		newTabLI = newTab.substring(newTab.indexOf('#')+1);

		$('li.ui-tabs-selected').removeClass('ui-tabs-selected');
		$('.'+newTabLI).addClass('ui-tabs-selected');

		$(this).parents('div.content').addClass('ui-tabs-hide');
		$(newTab).removeClass('ui-tabs-hide');

		return (false);
	});




	// Select Boxes
	$('div.filterDefaultHidden select').attr('disabled','true');
	$('.thumbFilters .radio').click( function () {
	$('div.filter select').attr('disabled','true');
	$('#'+$(this).attr('class').split(' ').slice(-1)).attr('disabled','');
	});



	// For the map pages on Careers
	$('ul.officeList a').click( function () {
	if (!$(this).parent('li').hasClass('selectedOffice')) {
		$('li.selectedOffice').removeClass('selectedOffice');
		$(this).parent('li').addClass('selectedOffice');
		$('.LOCshow').removeClass('LOCshow').addClass('LOChide');
		$('.'+$(this).attr('title')).removeClass('LOChide').addClass('LOCshow');
		redrawMap($(this).parent('li').children('div.geoMarker'));
	}
	return false;
	});



} // end Careers functionality







// Sets up insertion of flash on Careers home page



function loadSymbol(id, previouslyShown) {
	var flashvars2 = {};
	flashvars2.config_path = careersXMLFilePath + "config.xml";
	flashvars2.content_path = careersXMLFilePath + "content.xml";
	flashvars2.css_path = careersCSSFilePath + "unilever_careers.css";
	flashvars2.symbol_id = id;
	flashvars2.peviously_shown = previouslyShown;
	var params2 = {allowScriptAccess:"always", wmode:"transparent"};
	var attributes2 = {};
	swfobject.embedSWF(imageSoPath + "UnileverCareers.swf", "homepage-flash-version-content", "992", "490", "9.0.0", imageSoPath + "expressInstall.swf", flashvars2, params2, attributes2);

}

function symbolReady() {
	var myFlash = document.getElementById('homepage-flash-version-base');
	myFlash.symbolReady();
}


function showSymbol() {
	var ov = document.getElementById('homepage-flash-version-content-wrap');
	var bv = document.getElementById('homepage-flash-version-base-wrap');
	ov.style.zIndex = 2;
}

function unloadSymbol() {

	var flashvars2 = {};
	var params2 = {allowScriptAccess:"always"};
	var attributes2 = {};
	swfobject.embedSWF(imageSoPath + "empty.swf", "homepage-flash-version-content", "10", "10", "9.0.0", imageSoPath + "expressInstall.swf", flashvars2, params2, attributes2);

	var ov = document.getElementById('homepage-flash-version-content-wrap');
	var bv = document.getElementById('homepage-flash-version-base-wrap');
	ov.style.zIndex = 0;

	var myFlash = document.getElementById('homepage-flash-version-base');
	myFlash.showSymbolsMenu();
}

function setupFlashOnHomePage() {

	//Decide whether to embed flash on home page
	useFlash = function() {

		//don't embed flash if URL contains '#noFlash'
		var currentUrl = document.location.href;
		var linkToNoFlash = document.getElementById("linkToFallbackVersion");
		$('p.linkToFallbackVersion').removeClass("hidden");
		if ((varPointer = currentUrl.search("#")) !== -1){
			var variable = currentUrl.slice(varPointer+1);
			if (variable === "noFlash") {
				$('p.linkToFallbackVersion').remove();
				return false;
			}
		}

		//if required flash version and swjobject are detected, embed flash
		if ((typeof(swfobject) !== "undefined") && (swfobject.hasFlashPlayerVersion("9.0.115"))) {
			//insert 'low bandwidth version' link
			/*
			var linkParagraph = document.createElement("p");
			linkParagraph.className = "linkToFallbackVersion";
			linkParagraph.innerHTML = "<a href=\"#noFlash\" id=\"linkToFallbackVersion\">View non-flash version</a>";

			var content = document.getElementById("content");
			content.appendChild(linkParagraph);
			*/
			if (linkToNoFlash) {
				linkToNoFlash.onclick = function(){
					//change the URL to same with 'noFlash', then remove the flash content & show fallback content
					window.location.href = this.href;

					var flashVersion = document.getElementById("homepage-flash-version");

					if(flashVersion) {
						makePopBox();
						flashVersion.parentNode.removeChild(flashVersion);
						$(fallbackContent).removeClass("hidden");
						this.parentNode.parentNode.removeChild(this.parentNode);
					}
					
					return false;
				
				}

			}

			return true;
		}

		//otherwise, do not embed flash
		else {
			return false;
		}
	}

	//test for fallback content container
	var fallbackContent = document.getElementById("homepage-no-flash-version");
	
	if (hasFlashContent) {
		if (fallbackContent && useFlash()) {
			//Hide fallback content, insert flash content
			$(fallbackContent).addClass("hidden");
			
			var flashVersion = document.createElement("div");
			flashVersion.id = "homepage-flash-version";
			var flashVersionBaseWrap = document.createElement("div");
			flashVersionBaseWrap.id = "homepage-flash-version-base-wrap";
			var flashVersionBase = document.createElement("div");
			flashVersionBase.id = "homepage-flash-version-base";
			flashVersionBaseWrap.appendChild(flashVersionBase);
			var flashVersionContentWrap = document.createElement("div");
			flashVersionContentWrap.id = "homepage-flash-version-content-wrap";
			var flashVersionContent = document.createElement("div");
			flashVersionContent.id = "homepage-flash-version-content";
			flashVersionContentWrap.appendChild(flashVersionContent);
			flashVersion.appendChild(flashVersionBaseWrap);
			flashVersion.appendChild(flashVersionContentWrap);
			fallbackContent.parentNode.insertBefore(flashVersion, fallbackContent);
	
			var flashvars = {};
			flashvars.config_path = careersXMLFilePath + "config_base.xml";
			flashvars.content_path = careersXMLFilePath + "content.xml";
			flashvars.css_path = careersCSSFilePath + "unilever_careers.css";
			var params = {allowScriptAccess:"sameDomain", wmode:"opaque"};
			var attributes = {id:"homepage-flash-version-base", name:"homepage-flash-version-base"};
			swfobject.embedSWF(imageSoPath + "UnileverCareersBase.swf", "homepage-flash-version-base", "992", "490", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

		}
	} else {
		//Make non-flash version of page
	 	makePopBox();
	}
	if (fallbackContent) {
		//if fall back content is on current page, reset its style to visible
		fallbackContent.style.visibility = "visible";
	}
}

// Sets up non-flash version of Careers homepage
function getPopBoxList() {
	var PopBoxList = new Array();
	var j = 0;
	if(!document.getElementsByTagName) return false;
	var PopBoxTemp = document.getElementsByTagName('li');
	for (var i = 0; i < PopBoxTemp.length; i++) {
	    if (PopBoxTemp[i].className.indexOf('popbox') != -1) {
		  PopBoxList[j] = PopBoxTemp[i];
		  j++;
	    }
	}
	return PopBoxList;
}

// Sets up non-flash version of Careers homepage
function setPopBoxClass(PopBoxList,PopBoxClass) {
	for (var i = 0; PopBoxList.length > i; i++) {
		if (PopBoxList[i].className.indexOf(PopBoxClass) == -1) {
			PopBoxList[i].className = PopBoxList[i].className + " " + PopBoxClass;
		}
	}
}

// Sets up non-flash version of Careers homepage
function makePopBox() {
	var PopBoxList = getPopBoxList();
	setPopBoxClass(PopBoxList,'jsactive hidden');
	for (var i = 0; PopBoxList.length > i; i++) {
		PopBoxList[i].onclick = function() {
			if (this.className.indexOf('hidden') != -1) {
				setPopBoxClass(PopBoxList,'hidden');
				this.className = this.className.replace(" hidden","");
			} else {
				this.className = this.className + " hidden";
			}
		}
		PopBoxList[i].onmouseover = function() {
			if (this.className.indexOf('hover') == -1) {
				this.className = this.className + " hover";
			}
		}
		PopBoxList[i].onmouseout = function() {
			if (this.className.indexOf('hover') != -1) {
				this.className = this.className.replace(" hover","");
			}
		}
	}
}

// Detects if swfobject has been loaded from swfobject.js and whether the client has at least a flash version of 9
function hasFlashForVideo() {
	if ((typeof(swfobject) !== "undefined") && (swfobject.hasFlashPlayerVersion("9.0.0"))) {
		return true;
	} else {
		return false;
	}
}

// Finds video players on page and replace static images with flash videoplayers on Careers section
function setupVideoPlayers() {

	//find videoplayers
	var videoPlayers = $('div.videoPlayer');

	//loop through videos once, clone the videoplayer, destroy all flash objects
	//this is needed because on some pages a user can see videos on different tabs. Videos on hidden tabs must
	//be destroyed to avoid them from buffering when they can't even be seen
	videoPlayers
		.each(function(i){						
			
			//destroy all flash video objects
			$(this).children("object").remove();
			
			//get the the REQUIRED <img> tags inside the place holder, extract the video file name,
			//and then insert the video which has the exact same name. Thus:  img: myVideo.jpg gets myVideo.flv
			$(this).children("img")
				.each(function(){
					this.style.display="none";
					
					var videoPlayer=this.parentNode;					
					
					var imageUrl = this.src;
					var imageFileName = imageUrl.substring(imageUrl.lastIndexOf("\/")+1,imageUrl.lastIndexOf("\."))
					imageFileName = imageFileName.replace(videoSplashPostfix, '');		   
					if (hasFlashForVideo()) {
						
						var videoPlaceholder=$("<div class='videoPlaceHolder'></div>").appendTo(videoPlayer).get(0);
						
						//give video player an id						
						var thisVideoName = "video_" + i;
						videoPlaceholder.id = thisVideoName;

						var expressInstall = ""; //filePath + "resources/flash/expressInstall.swf";  //told not to implement update functionality
		
						var flashVersion = "9.0.0";       //this is the minimum flash version on which the video will work
		
						var videoPlayerSize;
						var videoWidth;
						var videoHeight;
		
						//check if player is small, large or XLarge, set size accordingly						
						var sizeClass=videoPlayer.className.replace("videoPlayer ","");
						switch (sizeClass){
							case "videoPlayerSmall":
								videoWidth = "226";
								videoHeight = "185";
								videoPlayerSize = imageSoPath + "UnileverVideoplayer-small.swf?r=" + new Date().getTime();						
							break;
							
							case "videoPlayerXLarge":
								videoWidth = "435";
								videoHeight = "353";
								videoPlayerSize = imageSoPath + "UnileverVideoplayer-xtra.swf?r=" + new Date().getTime();	//UnileverVideoplayer-large.swf
							break;
							
							case "videoPlayerWide":
								videoWidth = "435";
								videoHeight = "272";
								videoPlayerSize = imageSoPath + "UnileverVideoplayer-16x9.swf?r=" + new Date().getTime(); 
							break;
							
							case "videoPlayerWideSmall":
								videoWidth = "312";
								videoHeight = "203";
								videoPlayerSize = imageSoPath + "UnileverVideoplayer-16x9_small.swf?r=" + new Date().getTime();
							break;
							
							default:
								videoWidth = "312";
								videoHeight = "253";
								videoPlayerSize = imageSoPath + "UnileverVideoplayer-large.swf?r=" + new Date().getTime();														
						}

		
						//set the video and static image urls
						//REQUIRED: names of video images need to be equal to the static image name and movie name inside videoplayer directory
						var flashvars = {
							videourl: (globalAssetsPath + imageFileName + ".flv"),     //flash movie file
							imageurl: (globalAssetsPath + imageFileName + videoSplashPostfix + ".jpg"),     //freeze frame for before play is clicked and video loaded
							autostart: "false"
						};
		
						var params = {};
						params.menu = "false";
						params.wmode = "transparent";
						var attributes = {};
		
						swfobject.embedSWF(videoPlayerSize, thisVideoName, videoWidth, videoHeight, flashVersion, expressInstall, flashvars, params, attributes);						
					}							   
					else {
						if ($('div.noFlashPopup').length == 0) {
							$(videoPlayers).append('<div class="noFlashPopup"><div class="noFlashInner"><p>To view this content you require Adobe Flash.</p> <div class="highlightLink"><a href="http://get.adobe.com/flashplayer/?promoid=DXLUJ">Download from adobe.com</a></div></div></div>');
						}			
					}
				})
		})
		
	
}



// This function is responsible for adding functionality to drop down menu in the primary navigation
// It is essential that the in the HTML, there are exactly as many items in
// ul#primaryNav as ul#primaryNavExtension and their list items correspond exactly.
function  setupPrimaryNavigation() {

	// Variables
	var priNavElements = $('ul#primaryNav li');
	var priNavElementAnchors = $('ul#primaryNav li a');
	var priNavMenuSwitches = $('ul#primaryNav li span.switch');
	var priNavMenuTabs = $('ul#primaryNavExtension li.primaryNavExtensionTab');
	var priNavTimeout;
	var timeBeforeMenuAppears = 70;
	var timeBetweenMenuSwitch = 100;


	// Turn the primary nav menu 'on'
	$('ul#primaryNav').addClass('primaryNavMenusOn');


	// Open menus when arrow is hovered over
	priNavMenuSwitches.each(
		function(i){
			$(this).hover(

				function(){
					var rollOverStateClass;
					var openClass;
					var openMenuClass = "primaryNavExtensionTabOn";
					var openMenuClassSelected = "primaryNavExtensionTabOnSelected";

					//Different classes need be applied if item is selected
					if ($(priNavElements[i]).hasClass('selected')){
						rollOverStateClass = "rollOverSelected";
						openedClass = "openedSelected";
					} else {
						rollOverStateClass = "rollOver";
						openedClass = "opened";
					}

					//Add roll over state
					$(priNavElements[i]).addClass(rollOverStateClass);

					//Clear last time, start new one, then close all open menus, open selected menu
					window.clearTimeout(priNavTimeout);
					priNavTimeout = window.setTimeout (function(){
						var timeBeforeMenuLoads = whichTimeToUseForMenu();
					//	closeMenus();
						$(priNavElements[i]).addClass(openedClass);
						setTimeout(function(){
							if ($(priNavElements[i]).hasClass('selected')) {
								$(priNavMenuTabs[i]).addClass(openMenuClass);
								$(priNavMenuTabs[i]).addClass(openMenuClassSelected);
							} else {
								$(priNavMenuTabs[i]).addClass(openMenuClass);
							}
							$(priNavElements[i]).addClass('menuIsOpen');
						}, timeBeforeMenuLoads);
					}, timeBeforeMenuAppears );
				},

			// When arrow is rolled out of remove rollOver style and stop countdown to open menu
			function(){
				$(priNavElements[i]).removeClass("rollOverSelected");
				$(priNavElements[i]).removeClass("rollOver");
				window.clearTimeout(priNavTimeout);
			}
		);
	});

	// Close menus when item without menu is rolled over, or item with menu is rolled out of
	priNavElements.each(function(i){
		$(this).hover(
			function(){
				if(!($(this).hasClass("menuIsOpen"))){
					priNavTimeout = window.setTimeout (function(){
						closeMenus();
					},timeBeforeMenuAppears);
				}
			},
			function(){
				if($(this).hasClass("menuIsOpen")){
					priNavTimeout = window.setTimeout (function(){
						closeMenus();
					},timeBeforeMenuAppears);
				}
			}
		)
	});

	// Close menus when tabs are rolled out of, keep them open if roller onto
	priNavMenuTabs.each( function(i){
		$(this).hover(

		// When menu is hovered over clear timeout responsible for closing menu
		function(){
			window.clearTimeout(priNavTimeout);
		},

		// When menu is rolled out of start countdown to close menu
		function(){
			priNavTimeout = window.setTimeout (function(){
				closeMenus();
			},timeBeforeMenuAppears);
		});
	});


	// This function keeps the menu open when rolling over a primary nav anchor
	// only if the menu that is open belongs to that category
	priNavElementAnchors.each(function(i) {

		// Needs this condition, otherwise it would affect the worldmap anchor's hover functionality
		if (!$(this).hasClass("worldMap")) {
			$(this).hover(function(){
				var parentListItem = $(this.parentNode)[0];

				if ($(parentListItem).hasClass('menuIsOpen')) {
					window.clearTimeout(priNavTimeout);
				}
				else {
					priNavTimeout = window.setTimeout(function(){
						closeMenus();
					}, timeBetweenMenuSwitch);
				}

			}, 	function(){} );
		}

	});


	// When close button is clicked, close the menus
	$('a.primaryNavExtensionMenuClose').click(function(){
		closeMenus();
		return false;
	});



	//closes all menus
	function closeMenus(indexNumber) {
		$('li.opened').removeClass('opened');
		$('li.openedSelected').removeClass('openedSelected');
		$('li.primaryNavExtensionTabOn').removeClass('primaryNavExtensionTabOnSelected');
		$('li.primaryNavExtensionTabOn').removeClass('primaryNavExtensionTabOn');
		$('li.menuIsOpen').removeClass('menuIsOpen');
	}

	//Uses a different time to load a menu, depending if menu is alreay open or not
	function whichTimeToUseForMenu() {
		if($('li.primaryNavExtensionTabOn').length > 0) {
			return timeBetweenMenuSwitch;
		} else {
			return timeBeforeMenuAppears;
		}
	}
}

function setupSecondaryNavigation() {

	// Variables
	var secNavElement = $('div#secondaryNav div#secondaryNavCurrentSection');
	var secNavElementAnchor = $('div#secondaryNav div#secondaryNavCurrentSection a')
	var secNavSwitch = $('div#secondaryNav div#secondaryNavCurrentSection span.switch');
	var secNavMenu = $('div#secondaryNav ul#secondaryNavCurrentSectionMenu');
	var secNavMenuTabs = $('ul#primaryNavExtension li.primaryNavExtensionTab');
	var secNavTimeout;
	var timeBeforeMenuAppears = 100;


	// Turn the secondary nav 'on'
	$('div#secondaryNavCurrentSection').addClass('secondaryNavCurrentSectionMenuOn');

	// Open menu when arrow is hovered over, close it when rolled out
	secNavSwitch.hover(

		// Roll over
		function(){
			window.clearTimeout(secNavTimeout);
			secNavElement.addClass('secondaryNavCurrentSectionRollOver');
			secNavTimeout = setTimeout(function(){
					secNavMenu.addClass('secondaryNavCurrentSectionMenuOn');
			}, timeBeforeMenuAppears);
		},

		// Roll out
		function(){
			closeMenu();
		}
	);

	// Keep menu open when rolled over, close it when rolled out
	secNavMenu.hover(
		function(){
			window.clearTimeout(secNavTimeout);
		},
		function(){
			closeMenu();
		}
	);

	// Keep menu open when rolled over, close it when rolled out
	secNavElementAnchor.hover(
		function(){
			window.clearTimeout(secNavTimeout);
		},
		function(){
			closeMenu();
		}
	);


	function closeMenu(){
		secNavTimeout = setTimeout(function(){
				secNavMenu.removeClass('secondaryNavCurrentSectionMenuOn');
				secNavElement.removeClass('secondaryNavCurrentSectionRollOver');
		}, timeBeforeMenuAppears);
	}
}


// Sets up functionality on global search panel
function setupSearchFunctionality() {

	//On focus and blur display different values for input box
	$('div#globalSearch input.inputText').focus( function(){
			if (this.value === "" || this.value === $('div#globalSearch label')[0].innerHTML) {
			this.value = "";
		}
	});
	$('div#globalSearch input.inputText').blur( function(){
		if (this.value === "") {
			this.value = $('div#globalSearch label')[0].innerHTML;
		}
	});
}



function setupMapInHeader() {
	//Change location map text
	$('li.currentLocation a.worldMap').hover(
		function() {
				currentLocationText = $('li.currentLocation span')[0].innerHTML;
		  	$('li.currentLocation span')[0].innerHTML = $('li.currentLocation a.worldMap')[0].innerHTML;
		},
		function() {
		  	$('li.currentLocation span')[0].innerHTML = currentLocationText;
		}
	);
}



// Setup JavaScript for Unilever Worldwide module
function setupUnileverWorldWide() {

	// Turn the panel 'on'
	$('.unileverWorldWide').addClass('unileverWorldWideOn');

}


// Finds the tallest list item in each overview list. Sets its height on all shorter items.
function setupOverviewList() {

	$('div.hubOverviewList > ul').each(function(i){
		var tallestListItem = 0;
		
		$(this).children('li').each(function(i){
			if ($(this).height() > tallestListItem) {
				tallestListItem = $(this).height();
			}
		});

		$(this).children('li').each(function(i){	
			this.style.height = tallestListItem + "px";
		});
	
	});
	
}
//handles recipe results list row heights
function setupEqualHeightList() {
	$('ul.recipe-results li:last').css('border','0');
	$('ul.recipe-results').each(function(i){
		var listItems = $(this).children('li').length;
		var listItemsWidth = $(this).children('li')[0].offsetWidth;//to get padding
		var listWidth = $(this).width();
		var rowItems = Math.floor(listWidth / listItemsWidth);
		var rowCount = Math.ceil(listItems / rowItems);
		for(var i=1;i<=rowCount;i++){
			var tallestListItem = 0;
			for(var j=0;j<rowItems;j++){
				var index = i * rowItems - rowItems + j;
				if(index >= listItems){break;}
				if ($(this).children('li')[index].offsetHeight > tallestListItem) {
					tallestListItem = $(this).children('li')[index].offsetHeight;
				}
			}
			for(var k=0;k<rowItems;k++){
				var index = i * rowItems - rowItems + k;
				if(index >= listItems){break;}
				$(this).children('li')[index].style.height = tallestListItem + "px";
			}
		}
	});
}
function setupAdvSearch(){
	var selectHeight = $('fieldset.recipe-finder-advanced fieldset.recipe-finder-select').height();
	var optionsHeight = $('fieldset.recipe-finder-advanced fieldset.recipe-finder-options').height();
	if(selectHeight > optionsHeight){
		$('fieldset.recipe-finder-advanced fieldset.recipe-finder-options').height(selectHeight-2);
	}
	else{
		$('fieldset.recipe-finder-advanced fieldset.recipe-finder-select').height(optionsHeight+2);
	}
}

// Sets up site map and country selector pages
function setupPageSelector() {

	// Turn the page selector 'on'
	$('div.pageSelector').addClass('pageSelectorOn');

	// Functionality on nav buttons
	$('ul.pageSelectorNav li a').each(function(i){

		$(this).click(function(){
			var parent = $(this.parentNode);

			// Remove all selected nav items, make the newly clicked item selected
			$('ul.pageSelectorNav li').removeClass('selected');
			$(parent).addClass('selected');

			// Remove all selected section site maps, open selected one
			$('li.pageSelectorSection').removeClass('pageSelectorSectionSelected');
			$($('li.pageSelectorSection')[i]).addClass('pageSelectorSectionSelected');
			return false;

		});

	});
}

// Crops images in the hero panel on the About Us page
function setupFlashCropper() {

	if (!flashCrop) {
		return false;
	}

	if ($('body.stylesAboutUs div.heroPanelIssueStory > img').length > 0 ) {
		var tempImages = $('body.stylesAboutUs div.heroPanelIssueStory > img');
	}
	else {
		var tempImages = $('body.stylesMediaCentre div.heroPanelIssueStory > img');
	}
	if (tempImages.length > 0) {
		for (var i = 0; i < tempImages.length; i++) {
			var tempImage = $(tempImages[i]);
			var parentContainer = tempImage.parents("div.heroPanel");
			var tempContainerNumber = Number(parentContainer.attr("id").match(/\d+$/));
			var tempImageSrc = $(tempImages[i]).attr("src");
			var tempDivId = "image" + (tempContainerNumber);
			var tempContainer = $("div#" + tempDivId);
			if ($('body.stylesAboutUs div.heroPanelIssueStory > img').length > 0 ) {
				var maskURL = imageSoPath + "mask.png";
			}
			else if ($('body.stylesMediaCentre div.heroPanelIssueStory > img').length > 0 ) {
				var maskURL = imageSoPath + "mask-media.png";
			}
			
			var flashCropper = imageSoPath + "UnileverMasker-debug.swf";
			
			// Replace image with two divs, the inner one for flash replacement
			tempImage.wrap('<div class="imageReplacement"><div id="'+tempDivId+'"></div></div>');
			
			// Embed flash
			var flashvars = false;
			var params = {
			  menu: "false",
			  wmode: "transparent",
			  flashvars: "mask_url=" + maskURL + "&image_url=" + tempImageSrc
			};
			var attributes = {
				mask_url: maskURL,
				image_url: tempImageSrc
			};
			if ($('body.stylesAboutUs div.heroPanelIssueStory').length > 0 ) {
				swfobject.embedSWF(flashCropper, tempDivId, "492", "486", "9.0.0.0","", flashvars, params, attributes);
			}
			else if ($('body.stylesMediaCentre div.heroPanelIssueStory').length > 0 ) {
				swfobject.embedSWF(flashCropper, tempDivId, "391", "470", "9.0.0.0","", flashvars, params, attributes);
			}
		}
	}
	else {
	 return false;
	}
}

//Lines below here added by J Scott 18/09/2008.
//searchCheck - ensures that there is someting in the search box prior to sending it to the search results page
//checkNotFirst - Checks that the dropdown list is not on it's first value, which says '- Select your area -'
//----------------------------------------------------------------

var defQueryVal = 'Search';
var blank_pattern=/^[ \t\n]*$/;
function searchCheck(field) {
	if (field.value == defQueryVal)
	  {
		 field.value = '';
	  }
	if (blank_pattern.test(field.value))
	  {
		 alert('Please type the word(s) you wish to search for.');
		 field.focus();
		 return false;
	   }else
			out(field.value,'s',field.value);
   return true;
}

function checkNotFirst(oSelect) {
	var bNotFirst = false;
	if (oSelect) {
		if (oSelect.tagName == 'SELECT') {
			if (oSelect.selectedIndex > 0) {
				bNotFirst = true;
			}
		}
	}
	return bNotFirst;
}


//Ryan this is the new code.

if ( typeof unilever == 'undefined' ) { self.unilever = {}; }

unilever.homeTopic = {
	init: function() {
		$('div.homepageHeroPanels a.heroPanelOpenLink').each(function(i){
			// Check whether the current slide has a video, if so, attached the hasVideoX class
			var hasVideo=$(".heroPanelImage .videoPlayer").length>0;
			if(($('body').hasClass('stylesHomePage'+(i+1))) && (hasVideo)){
				$("body").addClass("hasVideo" + (i+1));
			}
			
			var hasVideoWide=$(".heroPanelImage .videoPlayerWide").length>0;
			if(($('body').hasClass('stylesHomePage'+(i+1))) && (hasVideoWide)){
				$("body").addClass("hasVideoWide" + (i+1));
			}
			
			$(this).click(function(){
				$('body').removeClass('stylesHomePage1');
				$('body').removeClass('stylesHomePage2');
				$('body').removeClass('stylesHomePage3');
				$('body').removeClass('hasVideo1');
				$('body').removeClass('hasVideo2');
				$('body').removeClass('hasVideo3');
				$('body').removeClass('hasVideoWide1');
				$('body').removeClass('hasVideoWide2');
				$('body').removeClass('hasVideoWide3');
				$('body').removeClass('hasTranscript1');
				$('body').addClass('stylesHomePage' + (i+1));
				//reset the flash players
				setupVideoPlayers();
				var hasVideo=$(this).parents(".heroPanel").find(".videoPlayer").length>0;
				if (hasVideo){
					$("body").addClass("hasVideo" + (i+1));
				}
				var hasVideoWide=$(this).parents(".heroPanel").find(".videoPlayerWide").length>0;
				if (hasVideoWide){
					$("body").addClass("hasVideoWide" + (i+1));
				}
				return false;
			});
		});
		
	}
}
unilever.brandTopic = {
	init: function() {
		unilever.brandTopic.menu();
		unilever.brandTopic.links();
	},
	menu: function() {
		$('div.hubHeroPanels ul.heroPanelPager li.ourBrandsFoodLink a').click(function(event){
			event.preventDefault();
			$('body').removeClass('stylesOurBrandsHome');
			$('body').removeClass('stylesOurBrandsPersonalCare');
			$('body').removeClass('stylesOurBrandsHomeCare');
			$('body').addClass('stylesOurBrandsFood');
			if ($('.hubHeroPanels').hasClass('hubHeroPanelsState2')) {
				$('.hubHeroPanels').addClass('hubHeroPanelsState1');
				$('.hubHeroPanels').removeClass('hubHeroPanelsState2');
			}			
		});
		$('div.hubHeroPanels ul.heroPanelPager li.ourBrandsPersonalCareLink a').click(function(event){
			event.preventDefault();
			$('body').removeClass('stylesOurBrandsHome');
			$('body').removeClass('stylesOurBrandsFood');
			$('body').removeClass('stylesOurBrandsHomeCare');
			$('body').addClass('stylesOurBrandsPersonalCare');
			if ($('.hubHeroPanels').hasClass('hubHeroPanelsState2')) {
				$('.hubHeroPanels').addClass('hubHeroPanelsState1');
				$('.hubHeroPanels').removeClass('hubHeroPanelsState2');
			}				
		});
		$('div.hubHeroPanels ul.heroPanelPager li.ourBrandsHomeCareLink a').click(function(event){
			event.preventDefault();
			$('body').removeClass('stylesOurBrandsHome');
			$('body').removeClass('stylesOurBrandsPersonalCare');
			$('body').removeClass('stylesOurBrandsFood');
			$('body').addClass('stylesOurBrandsHomeCare');
			if ($('.hubHeroPanels').hasClass('hubHeroPanelsState2')) {
				$('.hubHeroPanels').addClass('hubHeroPanelsState1');
				$('.hubHeroPanels').removeClass('hubHeroPanelsState2');
			}
		});
	},
	links: function() {
		$('.heroPanel .nextPageLink').click(function(event){
			event.preventDefault();
			$('.hubHeroPanels').addClass('hubHeroPanelsState2');
			$('.hubHeroPanels').removeClass('hubHeroPanelsState1');
		});
		
		$('.heroPanel .prevPageLink').click(function(event){
			event.preventDefault();
			$('.hubHeroPanels').addClass('hubHeroPanelsState1');
			$('.hubHeroPanels').removeClass('hubHeroPanelsState2');
		});
	}
}
unilever.ajaxTopic = {
	currentTopic: 1,
	topicCache: [],
	ajaxURL: null,
	topic: null,
	subTopic: null,
	nextTopic: null,
	previousTopic: null,
	location: null,
	init: function() {
		if ($('ul.heroPanelPager li a').length > 0) {
			unilever.ajaxTopic.coreTopic();
		}
		if ($('ul.heroPanelIssuePager li a').length > 0) {
			unilever.ajaxTopic.lowerTopic();
		}
	},
	coreTopic: function() {
		$('ul.heroPanelPager li a').each(function() {
			$(this).click(function (event) {
				event.preventDefault();
				unilever.ajaxTopic.ajaxURL = $(this).attr('href');
				unilever.ajaxTopic.location = $('div#heroPanel1');
				unilever.ajaxTopic.pager();
			});			
		});
	},
	lowerTopic: function() {
		$('ul.heroPanelIssuePager li a').each(function() {
			$(this).click(function (event) {
				event.preventDefault();
				unilever.ajaxTopic.ajaxURL = $(this).attr('href');
				unilever.ajaxTopic.location = $('div#heroPanel1');
				unilever.ajaxTopic.pager();
			});			
		});
	},
	pager: function() {
		unilever.ajaxTopic.topic = unilever.ajaxTopic.ajaxURL.match(/topic\=(\d+)/);
		unilever.ajaxTopic.subTopic = unilever.ajaxTopic.ajaxURL.match(/case\=(\d+)/);
		if ((unilever.ajaxTopic.topic != null) && (unilever.ajaxTopic.topic.length == 2)) {
    	unilever.ajaxTopic.topic = parseInt(unilever.ajaxTopic.topic[1]);
    } 
		else {
     unilever.ajaxTopic.topic = 0;
    }
		if ((unilever.ajaxTopic.subTopic != null) && (unilever.ajaxTopic.subTopic.length == 2)) {
     unilever.ajaxTopic.subTopic = parseInt(unilever.ajaxTopic.subTopic[1]);
    } 
		else {
     unilever.ajaxTopic.subTopic = 0;
		}
		unilever.ajaxTopic.previousTopic = unilever.ajaxTopic.topic -1;
		unilever.ajaxTopic.nextTopic = unilever.ajaxTopic.topic +1;
		if (unilever.ajaxTopic.previousTopic <= 0) {
			unilever.ajaxTopic.previousTopic = maxTopics;
		}
		if (unilever.ajaxTopic.nextTopic > maxTopics) {
			unilever.ajaxTopic.nextTopic = 1;
		}
		$('ul.heroPanelPager > li').each(function () {
			var urlTopic = 0;
			if ($(this).hasClass("prev")) {
				urlTopic = unilever.ajaxTopic.previousTopic;
			} 
			else if ($(this).hasClass("next")) {
				urlTopic = unilever.ajaxTopic.nextTopic;
			}
			var newTopic = $(this).children('a:first').attr('href').replace(/topic\=(\d+)/i, 'topic=' + urlTopic);
			if (newTopic.indexOf('http') == -1) {
				newTopic = unilever.ajaxTopic.ajaxURL.substring(0, unilever.ajaxTopic.ajaxURL.indexOf('?')) + newTopic;
			}
			$(this).children('a:first').attr('href', newTopic);
		});
		
		if (unilever.ajaxTopic.topic > 0) {
     if (unilever.ajaxTopic.subTopic == 0) {
      unilever.ajaxTopic.subTopic = 1;
     }
		 unilever.ajaxTopic.fetch();
    }
	},
	fetch: function() {
		var fetchFlag = false;
		unilever.ajaxTopic.ajaxURL = unilever.ajaxTopic.ajaxURL + '&ajax=true';
		for (i = 0; i < unilever.ajaxTopic.topicCache.length; i++ ) {
			if (unilever.ajaxTopic.ajaxURL === unilever.ajaxTopic.topicCache[i][0]) {
				unilever.ajaxTopic.location.html(unilever.ajaxTopic.topicCache[i][1]);
				fetchFlag = true;
				if ($('ul.heroPanelIssuePager li a').length > 0) {
					unilever.ajaxTopic.lowerTopic();
				}
				testFonts();
				setupFlashCropper();
				break;
			}
		}
		if (fetchFlag === false) {
			unilever.ajaxTopic.location.load(unilever.ajaxTopic.ajaxURL, function(){
				unilever.ajaxTopic.complete();
	 		});
		}
	},
	complete: function() {
		if ($('ul.heroPanelIssuePager li a').length > 0) {
			unilever.ajaxTopic.lowerTopic();
		}
		unilever.ajaxTopic.cache();
		testFonts();
		setupFlashCropper();
	},
	cache: function() {
		var cacheFlag = false;
		for (j = 0; j < unilever.ajaxTopic.topicCache.length; j++ ) {
			if (unilever.ajaxTopic.ajaxURL == unilever.ajaxTopic.topicCache[j][0]) {
				cacheFlag = true;
				break;
			}		
		}
		if (cacheFlag === false) {
			k = unilever.ajaxTopic.topicCache.length;
			unilever.ajaxTopic.topicCache[k] = new Array(
		    unilever.ajaxTopic.ajaxURL,
		    unilever.ajaxTopic.location.html());
		}
	}
}
function formHighlighter() {
	var requiredField = $('.required');
	requiredField.each(function(){
		var that = $(this);
		if (that.hasClass("inputGroup")) {
			var fField = that.find("label input");
			var fIndicator = that.find("p.label span");
			fField.focus(function() {
				fIndicator.addClass("PE_fieldHighlight");
			});
			fField.blur(function(){
				fIndicator.removeClass("PE_fieldHighlight");
			});
		} else {
			that.focus(function() {
				that.addClass("PE_fieldHighlight");
				indicator = that.siblings("span");
				indicator.addClass("PE_fieldHighlight");
			});
			that.blur(function(){
				var that = $(this);
				that.removeClass("PE_fieldHighlight");
				indicator = that.siblings("span");
				indicator.removeClass("PE_fieldHighlight");
			});
		}
	});
}