function submit_form(form_id)
{
    if( form_id == undefined || form_id == null ) return false;
    $('form#'+form_id).submit();
    return true;
}
function load_link(href)
{
    window.location  = href;
    return true;
}


////////////////////////////////////////// START *
function removeClass(obj,className)
{
	$(obj).removeClass(className);
}

function getMouseOverNavClass(oDom)
{
	var aClasses = oDom.split(' ');
	for(var i=0; i<aClasses.length; i++)
	{
		if( aClasses[i].indexOf('nav_') == 0 )
		{
			return aClasses[i];
		}
	}
}

function AddMouseOver(obj)
{
	$('ul#nav').removeClass();
	$('ul#subnav').removeClass();

	$('ul#nav').addClass(gActiveClass);
	$('ul#subnav').addClass('sn_'+gActiveClass);

	$('ul#subnav li.current_nav').css('opacity','0');
	$('ul#subnav li.current_nav').css('display','none');
	$('ul#subnav li').removeClass('current_nav');
	$('ul#subnav li.'+iNewSubnav).addClass('current_nav');
	$('ul#subnav li.'+iNewSubnav).css('opacity','0');
	$('ul#subnav li.'+iNewSubnav).css('display','block');
	$('ul#subnav li.'+iNewSubnav).css('opacity','1');
}

function RestoreMenuToDefault()
{
	gActiveClass = getMouseOverNavClass($('ul#nav li.sel a').parent().attr('class'));
	iNewSubnav = gActiveClass;

	$('#nav li a').removeClass('navHover');
	$('ul#nav,ul#subnav').removeClass();
	AddMouseOver(gActiveClass);
	$('ul#nav,ul#subnav').removeClass();
}
///////////////////////////////////////// END *

function submitCV(response_uri)
{
    window.open(response_uri,'scvs','width=500,height=370');
}

jQuery().ready(function(){
	//add the class to make the show/hide work on SCVS links. Because SCVS link cannot add class on the XML file.
	$('#subnav_scvs_Container').addClass('nav_0 current_nav');

   	//SCVS page - this is not working yet! need extra work.
   	$("div.scvsContainer ul.scvs_link_list li a, #subnav_scvs_Container a, li#jbe_leftcolumn_more_Container a").click(function(){
		submitCV($(this).attr('href'));
		return false;
	});

	//Grab the href, open it in a window and cancel the click action
	$("#footer_nav_FSCareers_Container a, #footer_nav_FSGroup_Container a").click(function(){
		window.open(this.href);
		return false;
	});

	//show the print button....
	$('div#content ul.jobOptions li a.print').css('display','block');
	$('div#content ul.jobOptions li a.print').click( function()
	{
		window.print();
		return false;
	});

	//handle the 'clicks' on the jobsearch/olr tabs
	$('div#leftColumn ul.tabs li a').click(function(){

		// Active - don't do anything....
		if( $(this).attr('class').indexOf('selected')>= 0 )
		{
			return false
		}
		$('div#leftColumn form.active').animate({opacity: "0"}, 1,function()
		{
			$(this).css('display','none');

			$('div#leftColumn form.noDisplay').css('opacity','0');
			$('div#leftColumn form.noDisplay').css('display','block');
			$('div#leftColumn form.noDisplay').animate({opacity: "100"},1,function()
			{
				$(this).removeClass('noDisplay');
				$(this).addClass('active');
			});
			$(this).addClass('noDisplay');
			$(this).removeClass('active');
		});

		$('div#leftColumn ul.tabs li a.selected').addClass('pending');
		$('div#leftColumn ul.tabs li a').addClass('selected');
		$('div#leftColumn ul.tabs li a.selected.pending').removeClass('selected');
		$('div#leftColumn ul.tabs li a.pending').removeClass('pending');

		return false;
	})

    if(typeof datepicker == "function"){
        //add the date picker start date on staff match
        $("#staff_start_date").datepicker({
            duration: "slow",
            dateFormat: "dd/mm/yy"
        });
    }

    //Get the current language of the site from the language menu
    var sSiteLang = $('ul#language_nav li.sel a').attr('href').toLowerCase().replace('/','');

    // don't display the check boxes on the olr
    // use images instead.
    $('table input[@type=checkbox]').each(function(){
         $(this).css('position', 'absolute');
         $(this).css('marginTop', '-999em');
         $(this).css('marginLeft', '-999em');

     $(this).parent('td').append('<img src="/img/lang/'+sSiteLang+'/btn/checkbox-off.gif" class="checkReplace">');
    });

    //check the hidden checkbox on td click
    //change the image to match
    $('#Form_OlrShortlist td.olr_ats').click(function(){
        if( $(this).attr('class') == 'olr_ats' )
        {

            switch( $(this).children('input').attr('checked') )
            {
                case true:
                $(this).find("input").attr('checked','');
                $(this).find("img").attr('src', $(this).find("img").attr('src').replace('-on.gif','-off.gif') )
                break;

                case false:
                $(this).find("input").attr('checked','checked');
                $(this).find("img").attr('src', $(this).find("img").attr('src').replace('-off.gif','-on.gif') )
                break;
            }
            // add a class to the short listed CV
            if (!$(this).children('input').attr('checked')){
            	$(this).parent().removeClass('addedCV');
            }else {
            	$(this).parent().addClass('addedCV');
            }
        }
        else
        {
        return true;
        }
    });

	//preload all mouseover form buttons
	$('form input[@type=image]').each(function(){
		if( $(this).attr('src').indexOf('spacer.gif') < 0 )
		{
			if( $('div#preLoad').attr('id') != 'preLoad' )
			{
				$('#wrapper').after('<div style="display:none;" id="preLoad"></div>');
			}
			$('#preLoad').prepend('<img width="1" height="1" src="'+$(this).attr('src').replace('-off.gif','-on.gif')+'"/>');
		}
	})

    //swap the form submission button[s] to over on mouseover
    $('form input[@type=image], img.onOff').mouseover(function(){
        if( $(this).attr('src').indexOf('-on.gif') <= 0 )
        {
            var NewSubmit = $(this).attr('src').replace('-off.gif','-on.gif');
            $(this).attr('src',NewSubmit);
        }
    });

    $('form input[@type=image], img.onOff').mouseout(function(){
        if( $(this).attr('src').indexOf('-off.gif') <= 0 )
        {
            var NewSubmit = $(this).attr('src').replace('-on.gif','-off.gif');
            $(this).attr('src',NewSubmit);
        }
    });

    //swap the form submission button[s] to active on form submission
    $('form input[@type=image]').click(function(){

        if( $(this).attr('src').indexOf('img/spacer')> 0 )
        {
            return true;
        }

        if( $(this).attr('src').indexOf('-active.gif')> 0 ) return false;

        var NewSubmit = $(this).attr('src').replace('-on.gif','-active.gif');
        var NewSubmit = $(this).attr('src').replace('-off.gif','-active.gif');
        $(this).attr('src',NewSubmit.replace('-on.gif','-active.gif'));


        if( $(this).attr('class') == 'click2animate' && $(this).parent('a').attr('id') != 'apply_top' && $(this).parent('a').attr('id') != 'apply_bot' )
        {
            setTimeout('load_link("'+$(this).parent('a').attr('href')+'")',1);
            return false;
        }
        else
        {
            setTimeout('submit_form("'+$(this).parents().filter('form').attr('id')+'")',1);
            return false;
        }

    });

    //Apply button actions....
    $('#JobSearch_ApplyTop,#JobSearch_ApplyBottom,.scv, .bar_submit_cv').click(function(){
        submitCV($(this).attr('href'));
        return false;
    });

	// Search Result page - style the whole row when mouseover.
	serpHover();

    //Home Page
    toggleFeaturedJobs();

    //Contact Us Office selected
    contactUsSelectedCountry();


	//toggle expanding text
	showHideText();

	//insert the label name into the input field. i.e. OLR email
	autoFill('#Form_OlrLogin_Email_Label', '#Form_OlrLogin_Email');
	//insert the error message into the input field. i.e. OLR Keyword
	autoFill('div#Form_Olr_ErrorMessages ul li', '#Form_Olr_Keywords');


	//////////////////////////////////// START **
	//original list is to show all the sub nav,
	//so run the restore default will allow it to display just the related sub nav.
	RestoreMenuToDefault();

	/**
	Resize random image left content
	*/
	if( $('.lhnPic img') )
	{
		$('.lhnPic').css('overflow','hidden');
		var sHeight = $('#innerContentContainer').height();
		if( sHeight < '600' ) {
			sHeight = '437'; //set the minimum height
		} else {
			sHeight = sHeight - 221; // reset the height to match the height of the content.
		}
		$('.lhnPic').css('height',sHeight+'px');
	}

	//hover the subnav...
	$('ul.subnav li a').hover(
		function(){
			if( typeof(iNewSubnav) != 'undefined' )
			{
				oLi = 'ul#nav li.'+iNewSubnav+' a';
			}
			else
			{
				oLi = 'ul#nav li a.sel';
			}
			$(oLi).addClass('mainNavOver');
			$('#nav').css("border-bottom-color", "#FF6600");

			if( typeof( tRestoreMenuToDefault ) == 'number' )
			{
				clearTimeout(tRestoreMenuToDefault);
			}
			//Global reset to the default menu display after 6 seconds
			tRestoreMenuToDefault = setTimeout("RestoreMenuToDefault()",6000);
		},
		function(){
			// we're on the current LIVE PAGE menu
			if( typeof(iNewSubnav) == 'undefined' || $('ul#nav li.sel').attr('class') == iNewSubnav )
			{
				$(oLi).removeClass('mainNavOver');
				$('#nav').css("border-bottom-color", "#3198A8");
			}
	})

	$('#nav li a').click(function()
	{
			if( typeof( tAddMouseOver ) == 'number' )
			{
				clearTimeout(tAddMouseOver);
			}
	});

	// hover the topnav
	$('#nav li a').hover(
		function(){

			if( typeof( tRestoreMenuToDefault ) == 'number' )
			{
				clearTimeout(tRestoreMenuToDefault);
			}

			//add the class to the nav and sub nav....
			gActiveClassNew = getMouseOverNavClass($(this).parent().attr('class'));

			if( $(this).parent().attr('class').indexOf('sel') == 0 )
			{
				RestoreMenuToDefault();
				return true;
			}

			//Global reset to the default menu display after 6 seconds
			tRestoreMenuToDefault = setTimeout("RestoreMenuToDefault()",6000);

			iNewSubnav = gActiveClassNew;

			// if this item is not the current parent page, then add another np class
			if( $(this).parent().attr('class').indexOf('sel') < 0 )
			{
				//alert('gActiveClassNew=' + gActiveClassNew);
				gActiveClassNew = gActiveClassNew+'_np';
				gNotDefaultPageMenu = true;
			}

			//remove any current class on the #nav and #subnav
			if( typeof(gActiveClass) != 'undefined' && gActiveClass != gActiveClassNew )
			{
				gOldClass = gActiveClass;
				$('#nav li a').removeClass('navHover');
			}

			gActiveClass = gActiveClassNew;
			$(this).addClass('navHover');
			tAddMouseOver = setTimeout("AddMouseOver('"+gActiveClass+"')",200);

			},
		function(){


			if( typeof( tAddMouseOver ) == 'number' )
			{
				clearTimeout(tAddMouseOver);
			}

			if( $(this).parent().attr('class').indexOf('sel') >= 0 )
			{
				$(this).removeClass('navHover');
				$('ul#nav,ul#subnav').removeClass();
			}
	});
	//////////////////////////////////// END **
});

function restorImg()
{

    $('img').each(function(){
        if( $(this).attr('restoreimage') == 'yes' )
        {
            $(this).attr('src',$(this).attr('src').replace('-active.gif','-on.gif'));
            $(this).attr('restoreimage','');
        }
    })
}

function GoToMap(sLocation)
{
	//get the current url
	if( window.location.href.indexOf('&') < 0 )
	{
		var sUrl = window.location.href+sLocation+'/';
	}
	else
	{
		var sUrl = window.location.href+'&option='+sLocation;
	}
	window.location = sUrl;
}
/*
EXAMPLE GOOGLE MAP ZOOM
function ZoomMap(sLocation)
{
        for (key in aOfficeLongLats)
        {
            if( key == sLocation )
            {
                var sOffice = key;
                aLatLong = aOfficeLongLats[key].split(',')
                var long = parseFloat(aLatLong[0]);
                var lat = parseFloat(aLatLong[1]);
            }
        }

        map.panTo(new GLatLng(long,lat));
        if( map.getZoom() == iZoom )
        {
            window.setTimeout(function() {
                  map.setCenter(new GLatLng(long,lat), 15);
            }, 1000);
        }

        var aClassNames = $('h1.location').attr('class').split(' ');
        for (i=0; i<aClassNames.length; i++)
        {
            if( aClassNames[i] != sOffice && aClassNames[i] != 'location' )
            {
                $('h1.location').removeClass(''+aClassNames[i]+'');
            }
        }
        $('h1.location').addClass(''+sOffice+'');
}
*/

// Sector tabs
function showSectorList(){
	$('div#filterBySector').css('borderColor','#CCCCCC');
	$('div#filterBySector ul#FeaturedJobsListNav').removeClass('hideall');
}
function hideSectorList(){
	$('div#filterBySector').css('borderColor','#FFFFFF');
	$('ul#FeaturedJobsListNav').addClass('hideall');
}
function toggleFeaturedJobs(){
	// Featured Job - filter by sector
	$('div#filterBySector').css('visibility','visible');
	$('div#filterBySector').click(function(){
		if ($('ul#FeaturedJobsListNav').attr('class').indexOf('hideall') >= 0) {
			showSectorList();
		}else {
			hideSectorList();
		}
	});

	//toggle featuredJobList
	$('div.colRight ul#FeaturedJobsListNav li a').click(function () {
		$('div.colRight ul.featuredJobsList:visible').hide();
		$('div.colRight ul li.on').removeClass('on');
		if ($(this).attr('id')){
			var activeTab = $(this).attr('id');
			$(this).parent().addClass('on');
			var active_li  = activeTab.replace('FeaturedJobs_','FeaturedJobsList_');
			var active_title  = activeTab + '_title';
			$('ul#' + active_li).show();
			hideSectorList();
			$('div.colRight div.FeaturedJobTitle span.cnr:visible').addClass('hideall');
			$('span.' + active_title).removeClass('hideall');
		}
		return false;
	});
}

function serpHover() {
	$(".tabularResults tbody tr").hover(function(){
		$(this).addClass('activeRowClick');
	}, function(){
		$(this).removeClass('activeRowClick');
	});

	//job search
	$("#JobSearchResults tbody tr").click(function(){
		var sTheLink = '/' + $(this).find(".JobSearch_job_title a").attr('href');
		window.location = sTheLink;
	});

	//staff search open CV window
    $('#Olr_SearchResults td.olr_jt').click(function(){
        window.open( '/' + $(this).children('a').attr('href'),'cand_cv', 'scrollbars=yes,width=700, height=600,resizable=yes');
        return false;
    });
}

function contactUsSelectedCountry() {
    //office selector: add class to the country of its city.
    $('div.colRight ul.pageMenu li ul.office li').each(function(){
        $("div.colRight ul.pageMenu li ul.office li.sel").parent().parent().addClass('selCountry');
    });
}


function showHideText() {
	$('ul.expandContent li a').css('display','inline');
	$('ul.expandContent li').css('cursor','pointer');
	// don't show the hide link
	$('ul.expandContent li a').find('span:eq(1)').css('display','none');

	$('ul.expandContent li').toggle(function(){
		var sMoreLink = $(this).children('a').find('span:eq(0)');
		var sHideLink = $(this).children('a').find('span:eq(1)');

		$(this).children('div').slideDown('fast');
		sMoreLink.hide();
		sHideLink.show();
		$(this).addClass('open');
		return false;
	}, function(){
		var sMoreLink = $(this).children('a').find('span:eq(0)');
		var sHideLink = $(this).children('a').find('span:eq(1)');

		$(this).children('div').slideUp('fast');
		sMoreLink.show();
		sHideLink.hide();
		$(this).removeClass();
		return false;
	})
}

// auto fill the form field
function autoFill(labelId, inputId){
	var v = $(labelId).text();
	$(inputId).attr({ value: v }).focus(function(){
		if($(this).val()==v){
			$(this).val("");
		}
	}).blur(function(){
		if($(this).val()==""){
			$(this).val(v);
		}
	});

}
