function repositionVertically(sContainerDiv)
{
		var contanier_height = $(sContainerDiv).height();
		var window_height = $(window).height();
		var margin_top = ((window_height - contanier_height)/2);

		if( margin_top >= 1 )
		{
			$('body').css('paddingTop','0px');
			$(sContainerDiv).css('marginTop',margin_top);
		}

		//preload niceform images...
		$.preloadImages("/site_img/niceforms/input_left.gif",
						"/site_img/niceforms/input_left_xon.gif",
						"/site_img/niceforms/input_right.gif",
						"/site_img/niceforms/input_right_xon.gif",
						"/site_img/niceforms/input_bg.gif",
						"/site_img/niceforms/input_bg_xon.gif"
						);
}

function getCountryLanguages(sLang)
{
	//remove all the existing language options...
	$("#selectLanguage option").each(function () {
		$(this).remove();
	});

	var aCountryLanguageOptions = window.aCountryLanguageOptions;
	var aOptions = Array();
	var aLangTitle = Array();

	for (key in aCountryLanguageOptions )
    {
        if( key == sLang )
        {
        	aOptions = aCountryLanguageOptions[key].split(',');
        	for ( i=0; i < aOptions.length; i++ )
        	{
        		aLangTitle =  aOptions[i].split('|');

		 		if(  aLangTitle[1].indexOf('-selected')>0 )
				{
					aLangTitle[1] = aLangTitle[1].replace('-selected','');
					$("#selectLanguage").html($("#selectLanguage").html()+'<option value="'+aLangTitle[0]+'" selected="selected">'+aLangTitle[1]+'</option>');
				}
				else
				{
					$("#selectLanguage").html($("#selectLanguage").html()+'<option value="'+aLangTitle[0]+'">'+aLangTitle[1]+'</option>');
				}
        	}
        }
    }
	$("#selectLanguage").attr('name',sLang+'_lang');
	$("#checkRemember").attr('name',sLang+'_remember');
	$("#checkRemember").attr('value','1');
	$("#SITE").attr('value',sLang);
}

$(document).ready(function(){




	//add the niceforms and thickbox css files...
	// helps css validation....
	$('meta[@name=keywords]').after('<link href="/css/niceforms.css" rel="stylesheet" type="text/css" media="all" />');
	$('meta[@name=keywords]').after('<link href="/css/thickbox.css" rel="stylesheet" type="text/css" media="all" />');

	jQuery.preloadImages = function()
	{
	  for(var i = 0; i<arguments.length; i++)
	  {
	    jQuery("<img>").attr("src", arguments[i]);
	  }
	}
	RunOnLoad(false);

	/*
	* Re-position the international landing page content based on the browser window size.
	*/
	if( $('div#international').attr('id') == 'international' )
	{
		//show the international landing page form
		$('div#international .form #language').css('display','block');

		//used to set the lauguage for the select language options box;
		getCountryLanguages( $("#selectCountry option:selected").attr('value') );
		$("#selectCountry").change(function () {
          $("#selectCountry option:selected").each(function () {
                getCountryLanguages($(this).attr('value'));
              });
        });
		repositionVertically('#international');
	}

	if( $('div#jbeLanding').attr('id') == 'jbeLanding' )
	{
		repositionVertically('#jbeLanding');
	}
	window.bOneDown = false;

	$('div#right ul.global_list li.option_group a').click(function(){

		//ensure that the user is not logged in as admin...
		//if they are then load this page normally so that they can edit the contents.
		if( window.bAdmin == true ) return true;
		var oThis = $(this).parent();

		//get all query data from the link
		var aQuery = $(this).attr('href').split('?');
		var aQueryPairs = aQuery[1].split('&');
		var aTemp,lang_site;
		for (i=0;i<aQueryPairs.length;i++)
		{
			aTemp = aQueryPairs[i].split('=');
			if( aTemp[0] == 'local_site' )
			{
				lang_site_val = aTemp[1];
				break;
			}
			delete aTemp;
		}

		//don't do anything if this option is already down
		if( $('input.local_site').attr('value') == lang_site_val ) return false;

		$('body').add('<span id="force">'+lang_site_val+'</span>');
		$('input.local_site').attr('value',lang_site_val);

		$('body').remove('#force');

		if( $('ul.global_list li.down a').attr('class') == 'selected' )
		{
			window.bOneDown = true;
		}

		if( window.bOneDown == false )
		{
			$(oThis).children('ul').fadeIn('slow');
			/* add a class to this so that we can close it later */
			window.bOneDown = true;
			$(oThis).addClass('down');
			$(oThis).children('a').addClass('selected');
		}
		else
		{
			$('ul.global_list li.down ul').fadeOut('fast',function(){
				$('ul.global_list li.down a.selected').removeClass('selected');
				$('ul.global_list li.down').removeClass('down');
				$(oThis).children('ul').fadeIn('slow');
				$(oThis).addClass('down');
				$(oThis).children('a').addClass('selected');
			});
		}

		return false;
	});

	$('#main_menu_nav .main_nav_action, #JobSearchResultsPanel a.jbeLink, #title-JobSearchDetails_back a.jbeLink').click(function(){

		//hide the tooltip in the form if visible
		hideToolTip();

		//hide any option boxes that are visible'
		hideOptionBoxesJQ();

		//this is admin so make the whole page loads.
		if( window.bAdmin == true )
		{
			return true;
		}

		//ensure that #hidden_content is not there!!
		$("#hidden_content").remove();

		var bJbeLink = false;
		var aClass = $(this).attr('class').split(' ');

		//set the current url as a var so we can discard reloading the same form requests.
		if( typeof(sCurrentModule) != 'undefined')
		{
			if( sCurrentModule == $(this).attr('href') )
			{
				scrollToJBE(aClass);
				//this is the same as the current module so don't do anything....
				return false;
			}
			else
			{
				sCurrentModule = $(this).attr('href');
			}
		}
		else
		{
			sCurrentModule = $(this).attr('href')
		}

		//remove the currently selected status
		$('ul#main_menu_nav a.main_nav_action').removeClass('selected');

		//remove all the old select boxes that niceforms has created
		var i=0;
		var tempName = '';
		$('.optionsDivInvisible').each(function(){
			tempName = $(this).attr('id').replace('optionsDiv','');

			//2 because 0 = country select, 1 = language select.
			if(tempName >= 2)
			{
				$(this).remove();
			}
		});


		if( aClass[0] == 'jbeLink' )
		{
			//scroll to the top of the page
			scrollToJBE(aClass);
			bJbeLink = true;

			var sSelectd = '#mm_jbe';
		}
		else
		{
			var sSelectd = this;
		}

			//change the active nav botton..
			$(sSelectd).addClass('selected');

		//get the height of the current #module_content
		var module_panel_height = parseFloat($("#module_panel").height());
		var module_panel_paddingTop = parseFloat($("#module_panel").css('paddingTop'));
		var module_panel_width = parseFloat($("#module_panel").width());

		$('#module_panel').css('height', module_panel_height );

		//fade out the current content
		$("#module_content").fadeOut('Slow',function (){

			//load in the loading animation
			$("#module_content").html('<img class="module_loadinganimation" src="/site_img/loadinganimation.gif"/>');

			//fade content back in
			$("#module_content").fadeIn('Slow');
		});

		//add an empty div to contain the new contents
		$('#module_panel').after('<div id="hidden_content" style="margin-left:-999em;position:absolute; width:'+module_panel_width+'"></div>');

		var aUrl = $(this).attr('href').split('/');
		var sUrl = '';

		// IF THE LANGUAGE IS PASSED IN AS THE FIRST ITEM OF THE RE-WRITTEN URL
		if( aUrl[0] == '' &&  aUrl[1] != '' && aUrl[2] != '' && aUrl[3] != '' &&  aUrl[4] == '' )
		{
			//if url rewriting is on we need to turn the href into something that jQuery understands
			sUrl = '/index.php?Mode='+aUrl[2]+'.'+aUrl[3]+'&lang='+aUrl[1];
		}
		else if( aUrl[0] == '' &&  aUrl[1] != '' && aUrl[2] != '' &&  aUrl[3] == '' )
		{
			//if url rewriting is on we need to turn the href into something that jQuery understands
			sUrl = '/index.php?Mode='+aUrl[1]+'.'+aUrl[2]+'&lang='+$('#siteLanguage').html();
		}
		else
		{
			sUrl = $(this).attr('href')+'&lang='+$('#siteLanguage').html();
		}

		$("#hidden_content").load( sUrl+ '&jq=true #module_content_inner', function(){

		//alert( $("#hidden_content").html() );

			//hide the submit button!!
			$("#hidden_content input[@type=image]").css('display','none');

			$('#module_panel').animate({height: $("#hidden_content").height() });

			$("#module_content").fadeOut('Slow',function (){
				$("#module_content").html( $("#hidden_content").html() );
				$("#hidden_content").remove();

				RunOnLoad();

			});

			$("#module_content").fadeIn('Slow',function(){



				//put the submit button back in
				$("#module_content input[@type=image]").fadeIn('fast');

				swapBorder();
				clearInputFields();
				$('#module_panel').css('height','');

			});

		});

		return false;

	});


	//bookmark this site script
	$('li#book_mark_this_site a').click( function(){
		var url = $('span#header_url').html();
		var title = "Huxley Associates";

		if (window.sidebar)
		{ // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url,"");
		}
		else if( window.external )
		{ // IE Favorite
			window.external.AddFavorite( url, title);
		}
		else if(window.opera && window.print)
		{ // Opera Hotlist
			return true;
		}
		return false
	})
});


function scrollToJBE()
{
	$('html, body').animate({scrollTop:'0px'}, 1500, 'linear');
}
function checkForRequred(form_id)
{

	var returnBoolean = true;
	var form = '';
	if( form_id )
	{
		form = '#'+form_id+' ';
	}

	var bHide = true;

	$(form+'input[@type=text],'+form+'select').each(function () {

		bHide = false;

		var check_name = GetDefaultText( $(this).attr('name').replace('element_','') );

		var bEamil = true;
		var bShowRequired = false;
		if( ($(this).attr('name') == 'element_email' || $(this).attr('name') == 'element_sender_email' || $(this).attr('name') == 'element_recip_email'  ) && $(this).val() != check_name && $(this).val() != '' )
		{
			//get the div element that holds the error div for this email box
			//because there might be 2+ emails on a page...
			var failEmailDiv = $(this).parent().children('.emailFail');
			if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($(this).val())){
				if(failEmailDiv.attr('class').indexOf('show') <= 0 )
				{
					// we might actually want this to show
					// i.e. olr registration, email address exists in db
					failEmailDiv.fadeOut('slow');
				}
				//else
				{
					//set the flag 'bEamil' so that we can set the error color
				//	bEamil = false;
				}
			}
			else
			{
				bEamil = false;
				if( failEmailDiv.css('display') != 'block' )
				{
					failEmailDiv.fadeIn('slow');
				}
			}
		}

		//if the text field is empty or contains the default value
		if( bEamil == false || $(this).attr('rel') == 'required' && ( $(this).val() == check_name || $(this).val() == '' ) )
		{
			$(this).parent().css('borderColor','#DC1F64');
			returnBoolean = false
		}
		else if ($(this).attr('rel') == 'required' &&  $(this).val() != check_name && $(this).val() != '' )
		{
			$(this).parent().css('borderColor', '#003A63');
		}

	});

	if( bHide == true )
	{
		hideToolTip();
	}

	return returnBoolean;
}

	function GetDefaultText(name)
	{
		var sValue = '';
		$('form input[type=hidden]').each(function(){

			if( $(this).attr('name').replace('_initial','') == name )
			{
				sValue =  $(this).attr('value');
			}
		});
		return sValue;
	}

function RunOnLoad()
{

	//remove the border from element_keywords for olr and jbe as they are not required
	$('form#jobsearch_form #menuBlock_keywords, form#olrform .text_input').css('border','0px');

	//hide the text/checkbox for the add to shortlist
	$('.addCv').addClass('addCvAdvanced');

	// for the contact_office page
	// hides/shows the offices
	$('div#main_content_col_2 #contact_offices li a.country_contact').click(function(){

		var oThis = $(this).siblings(".office_list");

		$('div#main_content_col_2 #contact_offices li a.country_contact').each(function(){

			if( $(this).siblings(".office_list").css('display') != 'none' )
			{
				$(this).siblings(".office_list").slideUp('slow');
			}
		})

		$(oThis).slideDown('slow');
		return false;
	});


	//Load the office details into the main content
	$('div#main_content_col_2 #contact_offices li ul li a').click(function(){

		//ensure that the user is not logged in as admin...
		//if they are then load this page normally so that they can edit the contents.
		if( window.bAdmin == true ) return true;

		//remove 'active' from all li a's
		$('#contact_offices li ul li a').removeClass('active');

		//add class to this clicked link;
		$(this).addClass('active');

		//fade out the current content
		$("#main_contnet_col_1").fadeOut('Slow',function (){

			//load in the loading animation
			$("#main_contnet_col_1").html('<img style="margin:0px auto;" src="/site_img/loadinganimation.gif"/>');

			//fade the animation in.
			$("#main_contnet_col_1").fadeIn('slow');
		});

		//inset the new contents into the #main_contnet_col_1;
		$("#main_contnet_col_1").load( $(this).attr('href')+ ' #main_contnet_col_1', function(){

			$('#main_contnet_col_1 #contact_details').css('fontSize','1.2em');

		});

		return false;

	});


	//check the hidden checkbox for this cv
	$('.addCv').click(function(){
		var bg = $(this).css('backgroundImage');
		var cb = $(this).children('input[@type=checkbox]');

		if(bg.indexOf('added-') > 0 )
		{
			$(this).css('backgroundImage',bg.replace("added-", "add-"))
			$(cb).attr('checked','');
		}
		else
		{
			$(cb).attr('checked','checked');
			$(this).css('backgroundImage',bg.replace("add-", "added-"))
		}

	});



	//open apply page in new window
	$('a.apply').click(function(){
		window.open($(this).attr('href'),'cva','width=500,height=370');
		return false;
	})

	//highlight required fields
	$('input[@type=text],select').each(function () {

		var check_name = GetDefaultText( $(this).attr('name').replace('element_','') );
		if( $(this).attr('rel') == 'required' && ( $(this).val()== '' || ($(this).attr('type') == 'text' && check_name == $(this).val())) )
		{
			$(this).parent().css('borderColor','#DC1F64');
		}
	});



	//run the niceforms
	if( typeof(niceforms_init) == 'function' )
	{
		niceforms_init(false);
	}

	//ensure that the form fields are fill out...
	$('form').submit(function(){

			//hide the tool tip...
			hideToolTip();

			var bFormOK = checkForRequred(this.id);
			if( bFormOK )
			{
				//remove all the _initial hidden fields.
				$('.default_text').remove();

			}
			return bFormOK;
	});

	$(".on_off").mouseover(function()
	{
		if(typeof(this.src) != 'undefined')
		{
			this.src = this.src.replace("-off", "-on")
		}
		else if( typeof ($(this).css('backgroundImage')) !=  'undefined')
		{
			var bg = $(this).css('backgroundImage');
			$(this).css('backgroundImage',bg.replace("-off.", "-on."))
		}
	});

	$(".on_off").mouseout(function()
	{
		if(typeof(this.src) != 'undefined')
		{
			this.src = this.src.replace("-on", "-off")
		}
		else if( typeof ($(this).css('backgroundImage')) !=  'undefined')
		{
			var bg = $(this).css('backgroundImage');
			$(this).css('backgroundImage',bg.replace("-on.", "-off."))
		}
	});


	//add magentaBorder border to all module_panel input/submit images
	$("#hidden_content input[@type=image],#module_panel input[@type=image], #emailAFriend-send input[@type=image]").each(function(){

		if( $(this).attr('id') != 'pseudobutton' )
		{
			$(this).addClass('magentaBorder');
		}

	});

	swapBorder();
	clearInputFields();
}

function clearInputFieldsMaster(obj)
{

	/**
	* Don't show the tool tip for the seclect boxes!!
	**/
	if( $(obj).attr('class') != 'selectButton' )
	{
		//javascript var has been set on the page
		var check_name = GetDefaultText( $(obj).attr('name').replace('element_','') );
		if( $(obj).val() == 'text' )
		{
		 	check_value = $(obj).attr('value');
		}
		else
		{
			check_value = $(obj).html();
		}

	    if( check_name == $(obj).attr('value') )
	    {
	    	$(obj).attr('value', '')
	    }
    }
    checkForRequred();
    CheckForEmptyTextFields( obj.id );

}

function clearInputFields()
{
	$('input[@type=text],textarea,a.selectButton').blur(function () {
		clearInputFieldsMaster(this)
	});

	//clear text input box contents if it is the same as default
	$('input[@type=text],textarea,a.selectButton').focus(function () {

		if( $(this).attr('class') != 'selectButton' )
		{
			showToolTip(this);
		}
		else
		{
			hideToolTip()
		}
		clearInputFieldsMaster(this);
	});
 }

function hideToolTip(){
	$('#toolTip').fadeOut('fast');
}

function hideOptionBoxesJQ()
{
	//hide all open option boxes!!
	if($('.optionsDivVisibleModule').attr('id'))
	{
		var SelectOpen = $('.optionsDivVisibleModule').attr('id');
		$('#'+SelectOpen).addClass('optionsDivInvisible');
		$('#'+SelectOpen).removeClass('optionsDivVisibleModule');
	}
}



function showToolTip(obj)
{
	//clear any current time out for the tooltip
	if( typeof( toolTipTimeoutID ) != 'undefined' )
	{
		clearTimeout ( toolTipTimeoutID );
	}


	hideOptionBoxesJQ();
	if( $('#toolTip').attr('id') != 'toolTip' )
	{
		$('#header_container').before('<div id="toolTip"></div>');
	}

	$('#toolTip').fadeOut('fast', function()
	{
		var thisParent = $(obj);

		$('#toolTip').removeClass('toolTip_left');
		$('#toolTip').removeClass('toolTip_right');
		$('#toolTip').html('');

		var name = GetDefaultText( $(obj).attr('name').replace('element_','') );

		var oPosition = $(thisParent).position();
		var Parent_height = '30px';
		var Parent_width = ($(thisParent).width());
		var adj = 7;

		if( $(obj).parent().parent().parent().attr('id') != 'emailAFriend' )
		{
			if( (oPosition.left + Parent_width) > $('#module_content').width() )
			{
				$("#toolTip").css('marginLeft', (oPosition.left - Parent_width) - 10 );
				//$('#toolTip').addClass('toolTip_right');
				$('#toolTip').css('backgroundImage','url(/site_img/bg/tooltip_notLeft.png)');
			}
			else
			{
				$("#toolTip").css('marginLeft', (oPosition.left + Parent_width - 10) );
				//$('#toolTip').addClass('toolTip_left');
				$('#toolTip').css('backgroundImage','url(/site_img/bg/tooltip_left.png)');
			}
		}
		else
		{
			if( $(obj).attr('name') == 'element_sender_name' || $(obj).attr('name') == 'element_sender_email' )
			{
				$("#toolTip").css('marginLeft', (oPosition.left - Parent_width) + 405 );
				//$('#toolTip').addClass('toolTip_right');
				$('#toolTip').css('backgroundImage','url(/site_img/bg/tooltip_left.png)');
			}
			else
			{
				$("#toolTip").css('marginLeft', (oPosition.left - Parent_width) - 80);
				//$('#toolTip').addClass('toolTip_right');
				$('#toolTip').css('backgroundImage','url(/site_img/bg/tooltip_notLeft.png)');
			}
		}

		$("#toolTip").html(name);
		$("#toolTip").css('marginTop',oPosition.top + adj);


	$('#toolTip').fadeIn('fast',function(){
		toolTipTimeoutID = setTimeout ("hideToolTip()",2500);
	})

	});


}

function swapBorder()
{
	//swap form input submit button
	$("input[@type=image]").bind("mouseover",function(e)
	{
		if( $(this).attr('id') != 'pseudobutton' )
		{
			$(this).addClass('whiteBorder')
		}
	});

	$("input[@type=image]").bind("mouseout",function(e)
	{
		if( $(this).attr('id') != 'pseudobutton' )
		{
			$(this).removeClass('whiteBorder')
		}
	});
}

function html_entity_decode(str) {
	var ta=document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;
}

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;
}


/* check for empty text fields
 * Fill with the default text if empty and default text exists
 */
function CheckForEmptyTextFields(cur_obj_id)
{
	$('input[@type=text],textarea,select').each(function () {

		var check_name = GetDefaultText( $(this).attr('name').replace('element_','') );

		if( $(this).attr('name') == 'element_keywords' && readCookie( 'SearchCookie[keywords]' ) == 'NO_SEARCH_TERMS' )
		{
			//don't change this value; keywords is ment to be blank!!
		}
		else if( $(this).attr('value') == undefined  && check_name != '' && this.id != cur_obj_id )
		{
			if($(this).attr('type') == 'text' || this.constructor == '[HTMLTextAreaElement]')
			{
				$(this).attr('value', check_name)
			}
		}
	});
}

function var_dump(obj) {
   if(typeof obj == "object") {
      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
   } else {
      return "Type: "+typeof(obj)+"\nValue: "+obj;
   }
}//end function var_dump

function doLoad(url,type)
{
	// type can be:
	// refresh;
	// open_new
   	setTimeout( ""+type+"('"+url+"')", 4000 );
}

function refresh(url)
{
    var sLocation = url;
    window.location.href = sLocation.replace(/&amp;/g, '&');
 }

function open_new(url)
{
    var sLocation = url;
    window.open(sLocation.replace(/&amp;/g, '&'),'','toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
}