/********** Utility Functions ***************/
function AddCSSFile(fileNameAndPath)    {
    //adds a css file reference using only javascript, for cases where you forgot a css and you really need it, like in dynamic pages)
    // e.g. AddCSSFile('css/x-layout.css');
    var filename=fileNameAndPath,
        fileref=document.createElement("link");
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", filename);
    document.getElementsByTagName("head")[0].appendChild(fileref);
}

function GetCheckBoxString(checkBoxID)  {
	if (MyObject(checkBoxID) != null && MyObject(checkBoxID).checked)    {
	    return 'True'
	}   else    {
	    return 'False'
	}
}

function GetSelectedOptionText(selectControlID) {
    	return document.getElementById(selectControlID).options[document.getElementById(selectControlID).selectedIndex].text; 
}

function GetSelectedOptionTitle(selectControlID)    {
    return document.getElementById(selectControlID).options[document.getElementById(selectControlID).selectedIndex].title;
}

function GetSelectedOptionValue(selectControlID)    {
	return document.getElementById(selectControlID).options[document.getElementById(selectControlID).selectedIndex].value;
}
function GetSelectedOptionID(selectControlID)   {
	var ddl = document.getElementById(selectControlID);

	if (ddl) {
		return ddl.options[ddl.selectedIndex].id || '';
	}
}
function GetRadioValue(radioButtonID)   {
	if (typeof document.getElementsByName(radioButtonID) === 'undefined')  {
		return null;
	}
	var radioObj = document.getElementsByName(radioButtonID);
	for (var i = 0; i < radioObj.length; i++)   {
		if (radioObj[i].checked)    {
			return radioObj[i].value;
		}
		
	}
	return null;
}

/*********************************************************/

function KeyDownHandler(btn, evt)   { 

	evt = evt || event;
	var target = evt.target || evt.srcElement,
		keyCode = evt.keyCode || evt.which;

    // process only the Enter key
    if (keyCode == 13)  {
        // cancel the default submit
        
        evt.returnValue=false;
        evt.cancel = true;
		evt.cancelBubble = true;

        // submit the form by programmatically clicking the specified button
        targetThing =document.getElementById(btn);
        
        if (targetThing.tagName=='A' )  {
           if (targetThing.onclick != null) {
              targetThing.onclick();
           } 
           else {
              location.href = targetThing.href;
            }
        }
        else    {
            $('#' + btn).trigger('click');
            //targetThig.click();
        }
        return false;
    }
	return true;
}

function Flag(id)   {
	HeaderControl.Flag(id)
	document.location.reload() 	
}

function split_callback(res)    {
	var result = res.value

	if (result !== "")   {
		var listTokens = result.split('|')
		
		if (listTokens[0] === '0')  {
			alert(listTokens[1])
		}
		else    {
			document.location.href = listTokens[1]
	    }
	}
}

function CloseRefreshParent() {
	// DOM is window.opener.document.location.reload()  ..... I think?
	window.parent.document.location.reload() ;
	window.close();
}

/********** Specific Control Referencing Functions ***************/
function SetPath(id)    {
	split_callback(PathwayControl.SetPathway(id));
}

function SetPathEmployer(id)    {
	split_callback(PathwayControl.SetPathwayEmployer(id));
}

function SetTargetJob() {
	split_callback(JobExtraControl.SetTargetJob());
}

function UnSetTargetJob()   {
	split_callback(JobExtraControl.UnSetTargetJob());
}

function UnSetCurrentJob()  {
	split_callback(JobExtraControl.UnSetCurrentJob());
}


function SelectAllPathCheckBoxes(chked)
{
    var parentNode = document.getElementById('PathwaysList'),
	    pathwayIds = ''; 
	for (i=0; i<parentNode.childNodes.length; i++)  {
		node = parentNode.childNodes[i].childNodes[0];
		if (node)   {
			node.checked = chked;		
		}
	}
}


function SearchForJobs()    {
	searchText  = Value('searchTerm');
	if (document.getElementById('txtQski').checked) {
		searchType  = 'ski';
	}
	if (document.getElementById('txtQual').checked) {
		searchType  = 'qual';
	}
	if (document.getElementById('txtQjob').checked) {
		searchType  = 'job';
	}
	sFunding = GetCheckBoxString('txtFunding');
	ReDirect(JobSearchControl.FireSearchForJobs(searchText, searchType, sFunding));
}

function SimpleSearchForJobs()  {
	searchText  = Value('searchTerm');
	ReDirect(JobSearchControl.FireSearchForJobs(searchText, 'job', 'False'));
}

function SimpleSearchForQualifications()    {
	sSearchText = escape(Value('courseName'));
	ReDirect(QualSearchControl.FireSearchForQualifications( 'Qual', '', sSearchText,  'No',  '',  false, false, false, false, false, false, false, false));
}
function ShowAllQualifications()    {
	ReDirect(QualSearchControl.FireSearchForQualifications( 'Qual', '', '',  'No',  '',  false, false, false, false, false, false, false, false));
}

function SearchForQualifications()  {
	var displayBy = GetSelectedOptionValue('displayBy'),
	    jobID = undefined;
	if (Value('JobName') === "") {
	    jobID =   '';
	    MyObject("JobRoleID").value = '';
	}
	else    {
	    jobID =   Value('JobRoleID');
	}
	
	var keyWord  = Value('keyWord'),
	    fundable  = "No", /*GetSelectedOptionValue('fundable');*/
	    courseType = GetSelectedOptionValue('courseType'),
	    chkPreEmp = MyObject("chkPreEmp").checked,
	    chkSafe = MyObject("chkSafe").checked,
	    chkWorkforce = MyObject("chkWorkforce").checked,
	    chkProg = MyObject("chkProg").checked,
	
	    chkEngland = MyObject("chkEngland").checked,
	    chkWales = MyObject("chkWales").checked,
	    chkNI = MyObject("chkNI").checked,
        chkScotland = MyObject("chkScotland").checked;
			
	ReDirect(QualSearchControl.FireSearchForQualifications(displayBy,  jobID,  keyWord,  fundable,  courseType, chkPreEmp, chkSafe,chkWorkforce , chkProg, chkEngland, chkWales, chkNI, chkScotland));
}

function CollegeQualPCSearch(sQual) {
	sPostCode = Value('postCode');
	if (GetSelectedOptionText('WithIn') === 'Any Distance') {
		sWithIn = '0';
	}
	else    {
		sWithIn  = GetSelectedOptionText('WithIn').split(' ')[0];
	}
	Place(QualificationsDisplayControl.FireCollegeQualPCSearch(sQual, sPostCode, sWithIn));
}

function ShowColleges(qualtype, qualID) {
	MyObject('CollegeSearchButtonWait' + qualID).style.display = 'inline';
	divID = 'CollegeList' + qualID;
	QualSearchResultsControl.FireGetColleges(qualtype, qualID, divID,ShowColleges_CallBack);
}
function ShowColleges_CallBack(res) {
	//MyObject('CollegeSearchButtonWait').style.display = 'none'
	Place(res);
}

function HideColleges(qualID)   {
	divID = 'CollegeList' + qualID;
	Place(QualSearchResultsControl.FireHideColleges(qualID, divID));
}
/********** Register User Functions ***************/

function CheckTerms()   {
	return document.getElementById('TermsConditionsRead').checked || false;
}

function RegisterNewUser(bType) {
	alert('Unreachable Code: Please contact Support');
};

function RegisterNewPerson()    {
	if (!CheckTerms()) {
		alert('You must agree with the sites terms and conditions before you can register.');
		return;
	}
   
	if (ValidateNewUserForm())  {
		//PlaceWaitButtonToggle('registerNewUserButton');
		MyObject('registerNewUserButtonWait').style.display="";
        //MyObject('regnewbtnpay').style.display="none";
        MyObject('regnewbtnfree').style.display="none";
        SpinMe(MyObject('regnewbtnfree'), "<strong>Creating Your Account, please wait...</strong>");
		
		var sFirstname = Value('fFirstName');
		    sSurname = Value('fSurname'),
		    sContactEmail = Value('fEmail'),
		    sPassword = Value('fPassword1'),
		    sVoucherCode = Value('fVoucherCode'),
            sAddress1 = Value('fAddress1'),
            sAddress2 = Value('fAddress2'),
            sAddress3 = Value('fTown'),
            sAddress4 = Value('fPostcode'),
            sAddress5 = Value('fCounty'),
            sAddress6 = Value('fCountry'),
		    fReceiveEmail = MyObject("fOptin").checked,
		    fReceiveInfoFromThirdParties = MyObject("fOptinThirdParty").checked,
		    bOptionEmailPref1 = document.getElementById('fOptinEmaiPref1').checked,
	        bOptionEmailPref2 = document.getElementById('fOptinEmaiPref2').checked,
	        bOptionEmailPref3 = document.getElementById('fOptinEmaiPref3').checked,
		    bJobSeeker18to24 = false,
		    bPreEmpoymentTraining = false,
		    sHowFound = $('#fHow').val(),
		    sHowFoundOther = Value('fWhereOther');
		// and all the other new fields!
		

		var userType = GetRadioValue('group1') || '';
		if (userType == 'SchoolStudent' || userType == 'CollegeStudent' || userType == 'UniversityStudent' || userType == 'Apprentice' || userType == 'YoungApprentice') {
		    var sCollege = GetSelectedOptionText('CollegeNameResults');
		    if (GetSelectedOptionValue('CollegeNameResults') == '-1')   {
		        sCollege = Value('fUnlistedCollege');   
		    }
		    var sCourse = GetSelectedOptionText('CourseNameResults');  
		    if (GetSelectedOptionValue('CourseNameResults') == '-1')    {
		        sCourse = Value('fUnlistedCourse'); 
		    }
		    var sIndustrySector = '';
		}
		else if (userType == 'Employee')    {
		    var sIndustrySector = GetSelectedOptionText('IndustrySector'),
		        sCollege = "";var sCourse = "";
		}
		else if (userType == 'NotWorking' && document.getElementById('petquestion').checked) {
		    var sCourse = ""; var sIndustrySector = '';
		    var sCollege = GetSelectedOptionText('PetCollegeNameResults');
		    if (GetSelectedOptionValue('PetCollegeNameResults') == '-1')   {
		        sCollege = Value('fPetUnlistedCollege');   
		    }
		    bJobSeeker18to24 = document.getElementById('jsa_18to24').checked;
		    bPreEmpoymentTraining = document.getElementById('petquestion').checked;
		}
		
		
	    else    {
		    var sIndustrySector = '';var sCollege = "";var sCourse = "";
		}

		RegisterNewControl.RegisterNewUser(userType, sPassword, sCollege, sCourse, sIndustrySector, sFirstname, sSurname, sContactEmail, sAddress1, sAddress2, sAddress3, sAddress4, sAddress5, sAddress6, fReceiveEmail, fReceiveInfoFromThirdParties, sVoucherCode, bOptionEmailPref1, bOptionEmailPref2, bOptionEmailPref3, bJobSeeker18to24, bPreEmpoymentTraining,sHowFound, sHowFoundOther, RegisterNewUser_callback);
	}						
	return true;
};


function RegisterStudent()  {
	if (ValidateNewUserForm())  {
		//PlaceWaitButtonToggle('registerNewUserButton');
		MyObject('registerNewUserButtonWait').style.display="";
        //MyObject('regnewbtnpay').style.display="none";
        MyObject('registerButton').style.display="none";
        
		var sUsername = Value('fUserName'),
		    sPassword = Value('fPassword1'),
		    sFirstname = Value('fFirstName'),
		    sSurname = Value('fSurname'),
		    sContactEmail = Value('fEmail'),
		    sContactTel = Value('fMobile'),
		/*var sVoucherCode = Value('fVoucherCode');*/
		    sCollege = Value('CollegeName'),
		    sCourse = GetSelectedOptionText('CourseName');
		
		RegisterStudentControl.RegisterStudent(sUsername, sPassword, sFirstname, sSurname, sContactTel,  sContactEmail,sCollege,sCourse, RegisterStudent_callback);
	}						
	return true;
};

function RegisterNewUser_callback(res)  {
	//Register_callback(res,'registerNewUserButton');
	ReDirect(res);
	MyObject('registerNewUserButtonWait').style.display="none";
    //MyObject('regnewbtnpay').style.display="";
    UnSpinMe(MyObject('regnewbtnfree'));
    MyObject('regnewbtnfree').style.display=""; 
}

function RegisterStudent_callback(result)   {
	//We have regsitered OK
	result = result.value;
	MyObject('registerNewUserButtonWait').style.display="none";
    MyObject('registerButton').style.display="";
	var listTokens = result.split('|')
	if (listTokens[0] === '0') {
		alert(listTokens[1]);
		this.UpdateAjaxSessionTimer();
	}
	else    {
	    //registered ok, so show them the code and attempt to close the browser.
	    Place(RegisterStudentControl.ShowUnlockCode(Value('fUserName')));
	}
}

function RegisterPPUser_callback(res)   {
	Register_callback(res,'registerPPUserButton');
}

function Register_callback(res,sourceButton)    {
	ReDirect(res);
	PlaceWaitButtonToggle(sourceButton);
}

/********** My Page Functions ***************/
function MyPagePreferencesEdit_callback(res)    {
	MyPageUserEdit_callback(res,'savePreferencesButton');
}

function MyPagePersonalDetailsEdit_callback(res)
{
	MyPageUserEdit_callback(res,'savePersonalDetailsButton');
	var result = res.value,
	    listTokens = result.split('|');
			
	if (listTokens[0] !== '0')
	{
		alert('Personal details have been saved.');
	}
}

function MyPageUserEdit_callback(res,sourceButton)
{
	PlaceWaitButtonToggle(sourceButton);
	AlertOnError(res);
}

function MyPageLoginEdit_callback(res)
{
	MyPageUserEdit_callback(res,'saveLoginDetailsButton');
}

function SaveLoginDetails()
{
	if (ValidateLoginDetails())
	{
		PlaceWaitButtonToggle('saveLoginDetailsButton');
	
		var sUserName = Value("fUserName"),
		    sUserPass = Value("fPassword1");

		UserLoginEditControl.SaveLogin(sUserName, sUserPass,MyPageLoginEdit_callback);
	}
}

function SavePersonalDetails()  {
	if (ValidateUserPersonalDetails())  {
		PlaceWaitButtonToggle('savePersonalDetailsButton');

		var sUserFirst = Value("fFirstName"),
		    sUserLast = Value("fSurname"),
		    sEmail = Value("fEmail"),
		    sAddress1 = Value("fAddress1"),
		    sAddress2 = Value("fAddress2"),
		    sTown = Value("fTown"),
		    sCounty = Value("fCounty"),
		    sPostcode = Value("fPostcode"),
		    sTel = Value("fTel"),
		    sDOB = Value("fDOB"),
		    sCountry = Value("fCountry"),
		    sGender = Value("fGender"),
		    sVoucherCode = "",
		    bJobSeeker18to24 = false,
		    bPreEmpoymentTraining = false,
            userType = GetRadioValue('group1') || '';

		if (userType === 'Student' || userType === 'Apprentice' || userType == 'SchoolStudent' || userType == 'CollegeStudent' || userType == 'UniversityStudent' || userType == 'YoungApprentice') {
		    var sCollege = GetSelectedOptionTitle('CollegeNameResults');
		    if (GetSelectedOptionValue('CollegeNameResults') == '-1') {
		        sCollege = Value('fUnlistedCollege');
		    }

		    var sCourse = GetSelectedOptionText('CourseNameResults');
		    if (GetSelectedOptionValue('CourseNameResults') == '-1') {
		        sCourse = Value('fUnlistedCourse');
		    }
		    var sIndustrySector = '';
		}
		else if (userType === 'Employee') {
		    var sIndustrySector = GetSelectedOptionText('IndustrySector'),
		        sCollege = "",
		        sCourse = "";
		}
		else if (userType == 'NotWorking' && document.getElementById('petquestion').checked) {
		    var sCourse = ""; var sIndustrySector = '';
		    var sCollege = GetSelectedOptionText('PetCollegeNameResults');
		    if (GetSelectedOptionValue('PetCollegeNameResults') == '-1') {
		        sCollege = Value('fPetUnlistedCollege');
		    }
		    bJobSeeker18to24 = document.getElementById('jsa_18to24').checked;
		    bPreEmpoymentTraining = document.getElementById('petquestion').checked;
		    sVoucherCode = $("#fVoucherCode").val();
		  
		}
		else {
		    var sIndustrySector = '',
		        sCollege = "",
		        sCourse = "";
		}
		UserPersonalDetailsControl.SavePersonalDetails(sUserFirst, sUserLast, sEmail, sAddress1, sAddress2, sTown, sCounty, sPostcode, sTel, sDOB,sCountry, sGender, userType,sCollege, sCourse, sIndustrySector, sVoucherCode,  bPreEmpoymentTraining,  bJobSeeker18to24,  MyPagePersonalDetailsEdit_callback);
	}
}

function SavePreferences()
{
	PlaceWaitButtonToggle('savePreferencesButton');
	
	var fReceiveEmail = MyObject("fOptin").checked,
	    fReceiveInfoFromThirdParties = MyObject("fOptinThirdParty").checked,
	    fEmailpref1 = MyObject("fOptinEmailPref1").checked,
	    fEmailpref2 = MyObject("fOptinEmailPref2").checked,
	    fEmailpref3 = MyObject("fOptinEmailPref3").checked;
	UserPreferencesControl.SavePreferences(fReceiveEmail,fReceiveInfoFromThirdParties, fEmailpref1, fEmailpref2, fEmailpref3,MyPagePreferencesEdit_callback);
}

// This one is handy, use it just like document.getElementsByTagName('tag')
document.getElementsByClassName = function(clsName) {
	var retVal = new Array(),
        elements = document.getElementsByTagName("*");

	for(var i = 0; i < elements.length; i++)    {
		if(elements[i].className.indexOf(" ") >= 0) {
			var classes = elements[i].className.split(" ");
			for(var j = 0; j < classes.length; j++) {
				if(classes[j] == clsName)   {
					retVal.push(elements[i]);
				}
			}
		}
		else if(elements[i].className == clsName)   {
			retVal.push(elements[i]);
		}
	}
	return retVal;
}

function TrimString(sInString) 
{
	sInString = sInString.replace( /^\s+/g, "" );	// strip leading
	return sInString.replace( /\s+$/g, "" );		// strip trailing
}

function findPosX(obj)
{
	var curleft = 0;
	if(obj.offsetParent)    {
		while(1){
		    curleft += obj.offsetLeft;
		    if(!obj.offsetParent)   {
			    break;
		    }
		    obj = obj.offsetParent;
		}
	}
	else if(obj.x)  {
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if(obj.offsetParent)    {
		while(1)    {
		    curtop += obj.offsetTop;
		    if(!obj.offsetParent)   {
			    break;
			}
		    obj = obj.offsetParent;
		}
	}
	else if(obj.y)  {
		curtop += obj.y;
	}
	return curtop;
}

//*********************************************************************
// Good Employer Guides
//*********************************************************************
function GetAllVacancies(EmpId)
{
	var ldng = document.getElementById('Loading');
	if (ldng)   {
        ldng.style.display = '';
    }
	GoodEmployerControl.ShowAllVacancies(EmpId, GetAllVacancies_Callback);
}

function GetAllVacancies_Callback(res)  {
	Split_callback(res, 'Loading');
}

function GetRatingsForEmployer()    {
	if (typeof EmpId !== 'undefined' )  {
		GetRatingsForLocation(EmpId);
	}
	else    {
		ReloadWindow();
	}
}

function ReshowProviderRatings()    {
	if (typeof CollegeId !== 'undefined' )   {
		Place(QualCourseControl.FireReshowProviderRatings(CollegeId, 'providerRating'));
	}
	else    {
		ReloadWindow();
	}
	document.location.hash='#RatingsBookmark';
}

function GetRatingsForLocation(EmpId)   {
	var ldng = document.getElementById('Loading2');
	if (ldng)   {
	    ldng.style.display = '';
	}
	
	var ddLocation	= document.getElementById('_selLocation'),
	    location	= (ddLocation) ? ddLocation.options[ddLocation.selectedIndex].value : 'All';
	
	if (window.GoodEmployerControl) {
		GoodEmployerControl.ShowRatingsByLocation(EmpId, location, GetRatingsForLocation_Callback);
    }
    
	if (window.GoodEmployerEditControl) {
		GoodEmployerEditControl.ShowRatingsByLocation(EmpId, location, GetRatingsForLocation_Callback);
    }
}

function GetRatingsForGroup(EmpId, LocationId, GroupId, QuestionType, RatedEntityOid)   {
	var ldng = document.getElementById('Loading2');
	if (ldng)   {
	    ldng.style.display = '';
    }
    
	var ddGrp = document.getElementById('_selGroup'),
	    group;

	if (GroupId && GroupId !== 0)    {
		group = GroupId;
		for (var i=0; i < ddGrp.options.length; i++)    {
			ddGrp.options[i].selected = (ddGrp.options[i].value == GroupId);
	    }
	}
	else    {
		group = ddGrp.options[ddGrp.selectedIndex].value;
    }
    
	if (window.GoodEmployerEmployeeRatingControl)   {
		GoodEmployerEmployeeRatingControl.ShowRatingsByGroup(EmpId, group, LocationId, QuestionType, RatedEntityOid, GetRatingsForGroup_Callback);
    }
}

function GetRatingsForGroup_Callback(res)   {
	Split_callback(res, 'Loading2');
	tabs();
}
function GetRatingsForLocation_Callback(res)    {
	Split_callback(res, 'Loading2');
}

function SaveRating(EmpId, questionId, userId, locationId, ratedEntityOid,ThisChk)  {
	var ldng = document.getElementById('Loading2');
	if (ldng)   {
	    ldng.style.display = '';
	}
	var ddLocation = document.getElementById('_selLocation'),
	    location = (ddLocation) ? ddLocation.options[ddLocation.selectedIndex].value : 'All';
	
	if (locationId && locationId.length > 0)    {
		location = locationId;
	}
		
	// Get all of the check box's for this employer question and make sure only the clicked on one is checked JP 07/01/08	
	$('.' + questionId).each( function() {
	    if (this === ThisChk) {
	        this.checked = true;
	    }else{
	        this.checked = false;
	    }
	});
	
	var bYes = false,
	    bNo = false,
	    bMaybe = false;
	
	// Check which one it is that has been clicked and transform the 5 box method to the old 3 box method for the code!
    switch ($(ThisChk).attr('id')){
        case questionId + '_Yes':
            bYes = true;
            break;
            
        case questionId + '_No':
            bNo = true;
            break;
            
        case questionId + '_Maybe':
            bMaybe = true;
            break;
            
        case questionId + '_Maybe_No':
            bNo = true;
            bMaybe = true;
            break;
       
        case questionId + '_Maybe_Yes':
            bYes = true;
            bMaybe = true;
            break;
    };
			
	if (window.GoodEmployerEditControl) {
		GoodEmployerEditControl.SaveRating(EmpId, location, questionId, bYes, bNo, bMaybe, userId, SaveRating_Callback);
	}
	if (window.GoodEmployerEmployeeRatingControl)   {
		GoodEmployerEmployeeRatingControl.SaveRating(EmpId, location, questionId, bYes, bNo, bMaybe, userId, ratedEntityOid, SaveRating_Callback);
    }
}
function SaveRating_Callback(res)   {
	var ldng = document.getElementById('Loading2');
	if (ldng)   { 
	    ldng.style.display = 'none';
    }
}

function SimpleSearchForEmployer()  {
	var txt = document.getElementById('employerText');
	if (txt)    {
		document.location.href = 'EmployerSearchResults.aspx?searchTerm=' + escape(txt.value);
	}
}

function SearchForEmployer()    {
	var url = 'EmployerSearchResults.aspx?',
	    qs  = '',
	    txt = document.getElementById('employerText');
	if (txt)    {
		qs = 'searchTerm=' + escape(txt.value);
	}
	
	var ind = document.getElementById('_selIndustry');
	if (ind && ind.value != '-1')   {
		qs += '&ind=' + escape(ind.value);
	}
	
	document.location.href = url + qs;
}

function QualPopupButtonAction(qualID)  {
	var prov = GetRadioValue('provider'),
	    Qual = GetRadioValue('Qual'),
	    sGrade = Value('QualGrade'),
	    courseDate  = Value('CourseDate');
	
	if (prov == "FreeText1")    {
		prov = Value('FreeText1');
	}
	if (Qual == "FreeText2")    {
		Qual = Value('FreeText2');
	}
	
	RelQualPopupControl.FireProviderDetailsChanged(qualID, prov, courseDate, Qual, sGrade);
	
	window.parent.hidePopWin();
	window.parent.RebuildMyQuals();
	//now redo the tags and reste the parent screen to the Quals section in case they wandered off somewhere
	window.parent.initPopUpElements(window.parent.document.getElementsByTagName('a'));
	window.parent.location.hash='#QualsBookmark';
}

function RebuildMyQuals()
{
    if (MyObject('MyApplications') != null) {
        //rebuild Job Application/profile quals section
        var res = MyApplicationControl.FireRebuildQualsSection();
        parts  = res.value.split('|');       
        document.getElementById(parts[0]).innerHTML = parts[1];
        //document.getElementById(parts[2]).innerHTML = parts[3];         
        EnableQualSorting();
    }
	else if (MyObject('VerifyQuals') == null)   {	
		Place(MyPageControl.FireRebuildQualsSection('RelQuals'));
	}
	else    {
		Place(TheirPageControl.FireRebuildQualsSection('RelQuals'));
		//Place(TheirPageControl.FireRebuildValidQualsSection('VerifyQuals'));
	}
}

function VerifyQual(qualID)
{
	MyRelevantQualDisplayControl.FireVerifyQual(qualID);
	Place(TheirPageControl.FireRebuildValidQualsSection('VerifyQuals'));
	//document.location.hash='#VerifyQualsBookmark';
}

function UnVerifyQual(qualID)
{
	MyRelevantQualDisplayControl.FireUnVerifyQual(qualID);
	Place(TheirPageControl.FireRebuildValidQualsSection('VerifyQuals'));
	//document.location.hash='#VerifyQualsBookmark';
}

function QualProviderSearch()   {
	var sSearch = Value('ProviderSearchText'),
	    existingFreeText = Value('FreeText1');
	if (sSearch.length > 2) {
		Place(RelQualPopupControl.FireBuildProviderRows(sSearch,existingFreeText,'DynamicProviderRows'));
	}
}

function QualSearch()   {
	var sSearch = Value('QualSearchText'),
	    existingFreeText = Value('FreeText2');
	if (sSearch.length > 2) {
		Place(RelQualPopupControl.FireBuildQualRows(sSearch,existingFreeText,'DynamicQualRows'));
	}
}

//inline job picking code
function EmployerJobEdit(sEmployeeID, sOldJobID, isCurrentJob)  {
	var result = TheirPageControl.FireJobEdit(sEmployeeID,false, sOldJobID, isCurrentJob);	
	Place(result);
}

function EmployerJobRefresh(sEmployeeID, sOldJobID, isCurrentJob)   {
	var result = TheirPageControl.FireJobEdit(sEmployeeID,true,sOldJobID, isCurrentJob);	
	Place(result);
}

function EmployerJobSave(sEmployeeID,sEmployeeRoleListID, isCurrentJob) {
	var sEmployeeRoleOID = GetSelectedOptionValue(sEmployeeRoleListID),
	    result = TheirPageControl.FireJobSave(sEmployeeID,sEmployeeRoleOID,isCurrentJob);	
	ReloadWindow();
}

function LinkToNextYNQuestion(Qid)
{
	Place(YesNoQControl.FireNextQuestion(Qid));
	if (typeof MyObject('YesButton') === 'undefined') {
	    if (typeof MyObject('FundingSection') !== 'undefined') {
		    MyObject('FundingSection').className = "todo done";
		}
	}
	else if (typeof MyObject('FundingSection') !== 'undefined')    {
		MyObject('FundingSection').className = "todo";
	}
}
function CharCount(sTextID, NumChars)
{
	var sCommentText = document.getElementById(sTextID).innerText,
	    iCount = NumChars - sCommentText.length;

	if (iCount < 0) {	
		document.getElementById(sTextID).innerText = sCommentText.substring(0,NumChars);
		document.getElementById('iCount').innerHTML = '0';						
	}
	else    {
		document.getElementById('iCount').innerHTML = iCount;
    }
    
	if (iCount <= 0)    {
		document.getElementById('CharCount').style.color = '#FF0000';
	}
	else    {
		document.getElementById('CharCount').style.color = '#666666';
    }
}

// Function used to recursively go through all elements in the DOM below a given element
// and call a given function passing it each element.
function walkTheDOM(node, func)     {
	func(node); 
	node = node.firstChild; 
	while (node)    { 
		walkTheDOM(node, func); 
		node = node.nextSibling; 
	} 
}

function ReturnHome()   {
    window.parent.location.href = "welcome.aspx";	
}

function ActivateAccount()  {
	var sUsername = document.getElementById('txtUsername').value,
	    sCode = document.getElementById('txtAvtivationCode').value;

	if (TrimString(sCode) == '')    {
		alert('Please provide an activation code.');
	}
	else {
		var res = HoldingPageControl.ActivateAccount(sUsername, sCode);

		location.href = res.value;
	}
}

function ResendActivationEmail()    {
	var sUsername = document.getElementById('txtUsername').value;

	if (TrimString(sUsername) == '') {
		alert('Please provide your username so that we can send you an email.');
	}
	else {
		Place(HoldingPageControl.ReSendActivationEmail(sUsername));
	}
}

function SelectEmployerSearch() {
	var sSearch = Value('EmployerSearchText');
	if (sSearch.length > 2) {
		Place(SelectEntityPopupControl.FireBuildEmployerRows(sSearch,'DynamicEmployerRows'));
	}
}

function RemoveMyEmployer() {
	SelectEntityPopupControl.FireEmployerDetailsChanged(-1);
	Place(RateMyEmployerControl.FireRebuildEmployerSection('EmployerSec'));
	MyObject('MyJobsSection').className = "todo ";
	initPopUpElements(window.parent.document.getElementsByTagName('a'));
	location.hash='#EmployerBookmark';
}

function SelectEmployerPopupButtonAction()  {
	var empId = GetRadioValue('employer');
	if (empId != null)  {
		SelectEntityPopupControl.FireEmployerDetailsChanged(empId);
	}
	
	window.parent.hidePopWin();

	window.parent.Place(RateMyEmployerControl.FireRebuildEmployerSection('EmployerSec'));
	
//	if (window.parent.MyObject('AllowEmployerAccess') == null )
//	{
//		window.parent.MyObject('EmployerSection').className = "todo ";
//	}
//	else
//	{
//		window.parent.MyObject('EmployerSection').className = "todo done";
//	}
	
	
	//now redo the tags and reste the parent screen to the Quals section in case they wandered off somewhere
	window.parent.initPopUpElements(window.parent.document.getElementsByTagName('a'));
	window.parent.location.hash='#EmployerBookmark';	
}



function ContactUs()
{
	var sFirstName	= document.getElementById('fFirstName').value || '',
	    sSurName	= document.getElementById('fSurName').value || '',
	    sEmailAdd	= document.getElementById('fEmailAddress').value || '',
	    sEmailAdd2	= document.getElementById('fConfirmEmailAddress').value || '',
	    sSubject	= document.getElementById('fSubject').value || '',
	    sComments	= document.getElementById('fComments').value || '';

	if (sEmailAdd !== sEmailAdd2) {
		alert('Your confirmation email address does not match, please check the spelling and try again.');
		return;
	}

	if (sFirstName === '' || sSurName === '' || sEmailAdd === '' || sEmailAdd2 === '' || sSubject === '' || sComments === '') {
		alert('Not all required fields have been filled in, please check and try again.');
		return;
	}

	Place(ContactUsControl.SendContactUs(sFirstName,sSurName,sEmailAdd,sSubject,sComments));
}


function ToggleShowHide(selectedDiv)
{
	try
	{
		currentDiv = document.getElementById(selectedDiv);
		if (currentDiv.style.display == "" || currentDiv.style.display == "none")
		{
			currentDiv.style.display = "block";
		} 
		else 
		{
			currentDiv.style.display = "none";
		}
	}
	catch (ex)
	{}
}

function ShowPDF(divBlock)
{
	//get the current html dump
	var ht;
	if (divBlock)
	{
		ht = MyObject(divBlock).outerHTML;
	}
	else
	{
		 ht = window.document.body.outerHTML;
	}
	PageAsPDF.ShowPDF(ht);
}
/* Added by Tom 13/07/07 for 
	super employee search filter report page */

	AutoList = function(results) {
		var listTokens = results.split('|'),
		    i = undefined, 
			AutoResults = new Array(listTokens.length),
			token = undefined;
		
		for(i=0; i < listTokens.length; i++) {
			if (listTokens[i] === '') {
				continue;
			}

			token = listTokens[i].split('&&');

			AutoResults[i] = {};
			AutoResults[i].id = token[0];
			AutoResults[i].text = token[1];
		}

		return AutoResults;
	};

	
	function ShowCreditReportDetails(sEventName)
    {
        var sdtFrom = Value('dtFrom'),
            sdtTo = Value('dtTo');
        if (GetRadioValue('rdoPopupType') == "Graph")   {
            var newPanel = AdminReportsControl.ShowCreditFlowDetailPanel(sdtFrom, sdtTo, sEventName, 999, true).value;
            MyObject('graphresults').innerHTML = newPanel;
            //if (MyObject('InfoPane999') == null)
            //{
            //    MyObject('CreditReportDetailsPanel').innerHTML = MyObject('CreditReportDetailsPanel').innerHTML + newPanel ;
       
            //}
            prepareGraph();
            OpenPaneAt(event, 500, 'InfoPane999', 200, -600,999);
            
            
            //try
            //{
                var theGraph = document.getElementById("amline");
                theGraph.style.zIndex=999;
                //var data = MyObject('HiddenGraphData').value;
              // theGraph.reloadData();
            //    theGraph.setData(data);
            //}
            //catch (exxc)
            //{
            //    alert('Failed to set Data due to error ' + exxc.Message);
            //}
        }
        else    {
            MyObject('graphresults').innerHTML = "";  //zap the graph window (as it will be blank thasnk to a flash related bug)
            PopupPanelCount = PopupPanelCount + 1;
            var sPanelNum = PopupPanelCount,
                newPanel = AdminReportsControl.ShowCreditFlowDetailPanel(sdtFrom, sdtTo, sEventName, sPanelNum, false).value;
        
            if (newPanel.substring(0,2) == '0|')    { 
                PopupPanelCount = PopupPanelCount + 1;
                alert('Unable to create a detailed report at this time.  Please check the reporting dates are valid');
            }    
            else    {
                MyObject('CreditReportDetailsPanel').innerHTML = MyObject('CreditReportDetailsPanel').innerHTML + newPanel ;
                OpenPane(event, 400, 'InfoPane' + sPanelNum, -430, -630, 10 + PopupPanelCount);
            }
        }
    }

    function prepareGraph() {
        
        // <![CDATA[		
        var so = new SWFObject("amline/amline.swf", "amline" , "400", "270", "8", "#FFFFFF");
        so.addVariable("path", "amline");
        so.addVariable("wmode", "window");
        so.addVariable("chart_id", "chart1" );		
        so.addVariable("settings_file", escape("amline/auditevent_settings.xml"));
        so.addVariable("data_file", escape("amline/auditevent_data.txt"));
  
        so.addVariable("preloader_color", "#999999");
        so.write("flashcontent");
        // ]]>   
    }


	function LoginPopWin() {
		var sUsername = document.getElementById('txtUserName').value,
			sPassword = document.getElementById('txtPassword').value;

		var sResult = NeedsLoginControl.Login(sUsername, sPassword).value;
		if (sResult !== '') {
			alert(sResult);
		}
		else {
			window.parent.location.reload();
		}
	}
    
    function GetAllStarRatedQuals(sID, iRating) {
		Place(GoodQualificationGuideControl.GetAllStarRatedQuals(sID, iRating));
		document.getElementById(sID+'Btn').innerHTML = '<a href="#">Viewing all</a>';
	}

	function LoadingNoStarQuals() {
		document.getElementById('noStarsQuals').innerHTML = '<li>Loading results.... please wait.</li>';
	}

	function LoadingFindQuals() {
		document.getElementById('qualFilterResult').innerHTML = '<li>Loading results....</li>';
	}

	function FindQualsByFilter(iNumResults) {
		var sTitle = document.getElementById('txtTitle').value || '',
			bUseTitle = document.getElementById('chkTitle').checked,
			sCatagory = GetSelectedOptionID('ddlQT') || '-1',
			bUseCatagory = document.getElementById('chkQT').checked,
			sStyle = GetSelectedOptionID('ddlLearningStyle') || '-1',
			bUseStyle = document.getElementById('chkLearningStyle').checked;

		if (!bUseTitle && !bUseCatagory && !bUseStyle) {
			alert('You must tick the check box\'s to say which options you want to search with.');
			return;
		}

		Place(GoodQualificationGuideControl.FindQualsByFilters(sTitle,bUseTitle,sCatagory,bUseCatagory,sStyle,bUseStyle,iNumResults));
	}


	
	function LoadingFindGoodProviders() {

	    $('#ProviderResults').html('<p>Loading new list... please wait.</p>');
	    document.getElementById('ProviderResults').scrollIntoView();
	}
//  Commented out JP 30/12/08 Dont think this is used any mroe but commented out for easy recovery if it is.
//  TODO:Delete at a later date when no issues have arouse
//	function NextProviderPage() {
//		var iCurrentPageNum = Math.round(parseInt(document.getElementById('pageSpan').innerHTML, 10)/10) + 1;
//		var maxrecs = parseInt(document.getElementById('totalProvs').innerHTML, 10);
//		var filter = document.getElementById('CompanyNameFilter').value;
//		
//		if ((iCurrentPageNum ) * 10 > maxrecs)
//		    iCurrentPageNum = iCurrentPageNum -1;  //prevent going too far
//		
//		var eDDL = document.getElementById('SelectedCareerLine'),
//			sPathwayID = eDDL.options[eDDL.selectedIndex].id.replace('pw','');
//		    
//		Place(GoodEmployerGuideControl.BuildTop10Paged(iCurrentPageNum, filter, sPathwayID));
//		//now figure out and show the number ranges
//		var from = (iCurrentPageNum * 10) + 1;
//		if ((from + 9) < maxrecs)
//		    maxrecs = from + 9;
//		document.getElementById('pageSpan').innerHTML = (maxrecs == 0 ? 0 : from  ) + " - " + (maxrecs);
//	}

//  Commented out JP 30/12/08 Dont think this is used any mroe but commented out for easy recovery if it is.
//  TODO:Delete at a later date when no issues have arouse
//	function PreviousProviderPage() {
//		var iCurrentPageNum = Math.round(parseInt(document.getElementById('pageSpan').innerHTML, 10)/10) - 1;
//		var maxrecs = parseInt(document.getElementById('totalProvs').innerHTML, 10);
//		var filter = document.getElementById('CompanyNameFilter').value;
//		var eDDL = document.getElementById('SelectedCareerLine'),
//			sPathwayID = eDDL.options[eDDL.selectedIndex].id.replace('pw','');
//			
//		if (iCurrentPageNum < 0) iCurrentPageNum = 0;
//		
//		Place(GoodEmployerGuideControl.BuildTop10Paged(iCurrentPageNum, filter, sPathwayID));
//		//now figure out and show the number ranges
//		var from = (iCurrentPageNum * 10) + 1;
//		if ((from + 9) < maxrecs)
//		    maxrecs = from + 9;
//		document.getElementById('pageSpan').innerHTML = (maxrecs == 0 ? 0 : from ) + " - " + (maxrecs);
//	}


    function NextTrainerPage() {
		var iCurrentPageNum = parseInt(document.getElementById('currentPage').value, 10),
			iTotalPages = parseInt(document.getElementById('totalPages').value, 10);

		if (iCurrentPageNum+1 >= iTotalPages) { return; }

		document.getElementById('page' + iCurrentPageNum).style.display = 'none';
		document.getElementById('page' + (iCurrentPageNum+1)).style.display = '';
		document.getElementById('currentPage').value = iCurrentPageNum+1;
		
		var iFirst = (iCurrentPageNum)*20+1;
		var iLast = document.getElementById('page' + (iCurrentPageNum+1)).getElementsByTagName('tr').length + iFirst - 3;
		document.getElementById('pageSpan').innerHTML = iFirst + '-' + iLast;
	}

	function PreviousTrainerPage() {
		var iCurrentPageNum = parseInt(document.getElementById('currentPage').value, 10),
			iTotalPages = parseInt(document.getElementById('totalPages').value, 10);

		if (iCurrentPageNum <= 1) { return; }

		document.getElementById('page' + iCurrentPageNum).style.display = 'none';
		document.getElementById('page' + (iCurrentPageNum-1)).style.display = '';
		document.getElementById('currentPage').value = iCurrentPageNum-1;
		
		var iFirst = (iCurrentPageNum-2)*20+1,
		    iLast = document.getElementById('page' + (iCurrentPageNum)).getElementsByTagName('tr').length + iFirst - 3;
		document.getElementById('pageSpan').innerHTML = iFirst + '-' + iLast;
	}

    // Commented out by JP 30/12/08 - I dont think this is used any more but for now commented for easy retreival.
	//function FilterProviderListByName(setChar) {
    //    if (setChar != null)
    //        document.getElementById('CompanyNameFilter').value = setChar; 
    //    
    //    var filter = document.getElementById('CompanyNameFilter').value;
    //    
    //    var eDDL = document.getElementById('SelectedCareerLine'),
	//		sPathwayID = eDDL.options[eDDL.selectedIndex].id.replace('pw','');
    //    
    //    var result = GoodEmployerGuideControl.BuildTop10Paged(0, filter, sPathwayID);
    //    Place(result);
    //    //now interrogate extra info about the result to set the max amount of records
    //    var maxrecs = result.value.split('|')[2];
    //    document.getElementById('totalProvs').innerHTML = maxrecs;
    //    if (10 < maxrecs)
	//	    maxrecs = 10
	//	document.getElementById('pageSpan').innerHTML = (maxrecs == 0 ? 0 : 1  ) + " - " + (maxrecs);
	//}
	
	function InputClearMe() {
	    if ( $('#HiddenInputClearer').val() !== "done") {
	        $('#our-rated-employers input').val("");
	        $('#HiddenInputClearer').val("done");
	    }
	}
	
	function PostCodeDisplaySwitcher()  {
	    if( $('#PoscodeSpan').is(':visible'))   {
	        $('#PoscodeSpan').hide();
	        $('#PoscodeSpan input').val('');
	        $('#LocationSpan').fadeIn('slow');
	    } else {
	        $('#LocationSpan').hide();
	        $('#LocationSpan input').val('');
	        $('#PoscodeSpan').fadeIn('slow');
	    }
	}
	
	function FilterGoodGuideByMasterSearch() {
        var sName = document.getElementById('CompanyNameFilter').value;
        
        var eDDL = document.getElementById('SelectedCareerLine'),
			sPathwayID = eDDL.options[eDDL.selectedIndex].id.replace('pw',''),
		    sCharVal = $('#CharToStart').val(),
		    sPostcode = $('#PostCode').val(),
		    iMilesOf = $('#MilesOf').val(),
		    sLocation = $('#Location').val();
		$('#PageShortcuts').html('<img id="EmployerLoading" src="images/uksp/GE_Loading.gif" />');
			        
        var result = GoodEmployerGuideControl.GoodEmployerMasterSearch(sName,sPostcode,iMilesOf,true,sLocation,false, sPathwayID, sCharVal,0);
        
        /*** Master Search Inputs ***/
        /*string sName, string sPostCode, int iMilesFrom, bool bSortNearestPC, string sLocation,
            bool bSortBestMatchedLocation, string sPathWayOID,string sLetter, int iResults*/
        
        
        Place(result);
        //now interrogate extra info about the result to set the max amount of records
        var maxrecs = result.value.split('|')[2],
            sPageShortcuts = result.value.split('|')[3];
            
        document.getElementById('totalProvs').innerHTML = maxrecs;
        if (10 < maxrecs)
		    maxrecs = 10
		document.getElementById('pageSpan').innerHTML = (maxrecs == 0 ? 0 : 1  ) + " - " + (maxrecs);
		$('#PageShortcuts').html(sPageShortcuts);
		
		$('#backPage')[0].onclick = GoodGuideMasterSearchPrevPage;
		$('#forwardPage')[0].onclick = GoodGuideMasterSearchNextPage;
		$('#ClearFiltersBtn').fadeIn('slow');
		
		return false;
	}
	function GoodGuideClearFilters()    {
		$('#PageShortcuts').html('<img id="EmployerLoading" src="images/uksp/GE_Loading.gif" />');
			        
        var result = GoodEmployerGuideControl.GoodEmployerMasterSearch("","",100000,false,"",false, "", "", 0);
        
        /*** Master Search Inputs ***/
        /*string sName, string sPostCode, int iMilesFrom, bool bSortNearestPC, string sLocation,
            bool bSortBestMatchedLocation, string sPathWayOID,string sLetter, int iResults*/
        
        Place(result);
        //now interrogate extra info about the result to set the max amount of records
        var maxrecs = result.value.split('|')[2],
            sPageShortcuts = result.value.split('|')[3];
            
        document.getElementById('totalProvs').innerHTML = maxrecs;
        if (10 < maxrecs)
		    maxrecs = 10
		document.getElementById('pageSpan').innerHTML = (maxrecs == 0 ? 0 : 1  ) + " - " + (maxrecs);
		$('#PageShortcuts').html(sPageShortcuts);
		
		$('#backPage')[0].onclick = GoodGuideMasterSearchPrevPage;
		$('#forwardPage')[0].onclick = GoodGuideMasterSearchNextPage;
		$('#ClearFiltersBtn').fadeOut('slow');
		
		return false;
	}
	
	function GoodGuideMasterSearchChangePage(iPage) {
		$('#PageShortcuts').html('<img id="EmployerLoading" src="images/uksp/GE_Loading.gif" />');
        var result = GoodEmployerGuideControl.GoodEmployerGuideMasterSearchMovePage(iPage - 1, 10);
        
        /*** Master Search Inputs ***/
        /*string sName, string sPostCode, int iMilesFrom, bool bSortNearestPC, string sLocation,
            bool bSortBestMatchedLocation, string sPathWayOID,string sLetter, int iResults*/
        
        Place(result);
        //now interrogate extra info about the result to set the max amount of records
        var maxrecs = result.value.split('|')[2],
            sPageShortcuts = result.value.split('|')[3];
            
		$('#PageShortcuts').html(sPageShortcuts);
            
        document.getElementById('totalProvs').innerHTML = maxrecs;
        if ((iPage)*10 < maxrecs)   {
		    maxrecs = (iPage)*10
		}
		document.getElementById('pageSpan').innerHTML = (((iPage-1)*10)+1) + " - " + (maxrecs);
		
		return false;
	}
	
function GoodGuideMasterSearchNextPage() {
        var iCurrentPageNum = Math.round(parseInt(document.getElementById('pageSpan').innerHTML, 10)/10) + 1,
		    maxrecs = parseInt(document.getElementById('totalProvs').innerHTML, 10);
		
		if ((iCurrentPageNum ) * 10 > maxrecs)  {
		    alert('No More Pages Left To Turn!');
		    return false;
		}
		$('#PageShortcuts').html('<img id="EmployerLoading" src="images/uksp/GE_Loading.gif" />');
		
        var result = GoodEmployerGuideControl.GoodEmployerGuideMasterSearchMovePage(iCurrentPageNum, 10);
        
        /*** Master Search Inputs ***/
        /*string sName, string sPostCode, int iMilesFrom, bool bSortNearestPC, string sLocation,
            bool bSortBestMatchedLocation, string sPathWayOID,string sLetter, int iResults*/
        
        Place(result);
        
        //now interrogate extra info about the result to set the max amount of records
        var maxrecs = result.value.split('|')[2],
            sPageShortcuts = result.value.split('|')[3];
            
        document.getElementById('totalProvs').innerHTML = maxrecs;
        if ((iCurrentPageNum+1)*10 < maxrecs)   {
		    maxrecs = (iCurrentPageNum+1)*10
		}
		document.getElementById('pageSpan').innerHTML = ((iCurrentPageNum*10)+1) + " - " + (maxrecs);
		$('#PageShortcuts').html(sPageShortcuts);
		
		return false;
	}
	
	function GoodGuideMasterSearchPrevPage() {
        
        var iCurrentPageNum = Math.round(parseInt(document.getElementById('pageSpan').innerHTML, 10)/10) - 1,
		    maxrecs = parseInt(document.getElementById('totalProvs').innerHTML, 10);
		
		if ((iCurrentPageNum ) * 10 < 0)    {
		    alert('No More Pages Left To Turn!');
		    return false;
		}
		$('#PageShortcuts').html('<img id="EmployerLoading" src="images/uksp/GE_Loading.gif" />');
		
        var result = GoodEmployerGuideControl.GoodEmployerGuideMasterSearchMovePage(iCurrentPageNum , 10);
        
        /*** Master Search Inputs ***/
        /*string sName, string sPostCode, int iMilesFrom, bool bSortNearestPC, string sLocation,
            bool bSortBestMatchedLocation, string sPathWayOID,string sLetter, int iResults*/
        Place(result);
        
        //now interrogate extra info about the result to set the max amount of records
        var maxrecs = result.value.split('|')[2],
            sPageShortcuts = result.value.split('|')[3];
            
        document.getElementById('totalProvs').innerHTML = maxrecs;
        
		document.getElementById('pageSpan').innerHTML = (((iCurrentPageNum)*10)+1) + " - " + ((iCurrentPageNum+1) * 10);
		$('#PageShortcuts').html(sPageShortcuts);
		
		return false;
	}
	
    function FilterTrainerListByName()
    {
        LoadingFindGoodProviders();
    
        var sProvName = document.getElementById('provName').value || '',
            typeFilter = GetSelectedOptionValue('ProviderTypeFilter');
            GoodProviderGuideControl.FilterProviderListByName(sProvName,typeFilter, function(res){
		        Place(res);
		        document.getElementById('totalProvs').innerHTML = document.getElementsByClassName('provRow').length.toString();
	            var iMax = Math.min(document.getElementsByClassName('provRow').length, 20);
		        document.getElementById('pageSpan').innerHTML = '1-' + iMax;    		
    		    document.getElementById('ProviderTypeFilter').scrollIntoView();
		    }   );

    }

	function FilterProviderListByPostCode() {
	    LoadingFindGoodProviders();
	   
	    var sPostCode = document.getElementById('provPostCode').value || '',
            typeFilter = GetSelectedOptionValue('ProviderTypeFilter');
	    var sWithinRange = '';
		if (GetSelectedOptionText('WithIn') === 'Any Distance') {
		    sWithinRange = '0';
		}
		else {
		    sWithinRange = GetSelectedOptionText('WithIn').split(' ')[0];
		}
		
		
		
		GoodProviderGuideControl.FilterProviderListByPostCode(sPostCode, typeFilter, sWithinRange, function(res){
		    Place(res);
		    document.getElementById('totalProvs').innerHTML = document.getElementsByClassName('provRow').length.toString();
		    var iMax = Math.min(document.getElementsByClassName('provRow').length, 20);
		    document.getElementById('pageSpan').innerHTML = '1-' + iMax;
		    document.getElementById('ProviderTypeFilter').scrollIntoView();
		
		}
		 );
		
	}

    function FilterTrainerListByType()
    {
        var typeFilter = GetSelectedOptionValue('ProviderTypeFilter');
        Place(GoodProviderGuideControl.Rebuild(typeFilter));
        document.getElementById('totalProvs').innerHTML = document.getElementsByClassName('provRow').length.toString();
		var iMax = Math.min(document.getElementsByClassName('provRow').length, 20);
		document.getElementById('pageSpan').innerHTML = '1-' + iMax;
    }
    
	function GoodEmployerByName(iNumResults) {
		var sName = document.getElementById('empName').value || '';

		Place(GoodEmployerGuideControl.GoodEmployerByName(sName,iNumResults));
		document.getElementById('currentSearchType').value = 'name';
	}

	function GoodEmployerByPathway(iNumResults) {
		var eDDL = document.getElementById('CareerLines'),
			sPathwayID = eDDL.options[eDDL.selectedIndex].id.replace('pw','');

		Place(GoodEmployerGuideControl.GoodEmployerByPathway(sPathwayID,iNumResults));
		document.getElementById('currentSearchType').value = 'pathway';
	}
    
    function GoodEmployerMasterSearch(iResults) {
        Place(GoodEmployerGuideControl.GoodEmployerMasterSearch('People', '', '', false, '',false, '','', 0));
        document.getElementById('currentSearchType').value = 'Master';
            /*** Master Search Variables (In Order) ***/
            /*string sName, string sPostCode, int iMilesFrom, bool bSortNearestPC, string sLocation,
            bool bSortBestMatchedLocation, string sPathWayOID,string sLetter, int iResults*/
    }

	function GoodEmployerByAlpha(sLetter, iNumResults) {
		Place(GoodEmployerGuideControl.GoodEmployerByAlpha(sLetter,iNumResults));
		document.getElementById('currentSearchType').value = 'letter:' + sLetter;
	}

	function GoodEmployerAllResults() {
		var sSearchType = document.getElementById('currentSearchType').value || '',
			sBits = sSearchType.split(':');

		if (sBits.length > 1) {
			sSearchType = sBits[0];
		}

		switch (sSearchType) 
		{
			case 'name' :
				GoodEmployerByName(-1);
				break;
			case 'pathway' :
				GoodEmployerByPathway(-1);
				break;
			case 'letter' :
				GoodEmployerByAlpha(sBits[1],-1);
				break;
		}
	}

	function chkQualsTitle() {
		var sTxt = document.getElementById('txtTitle').value;

		if (sTxt !== '') {
			document.getElementById('chkTitle').checked = true;
		}
		else {
			document.getElementById('chkTitle').checked = false;
		}
	}

	function chkQualType() {
		var sQT = GetSelectedOptionID('ddlQT');

		if (sQT !== 'qt-1') {
			document.getElementById('chkQT').checked = true;
		}
		else {
			document.getElementById('chkQT').checked = false;
		}
	}

	function chkLearnStyle() {
		var sLS = GetSelectedOptionID('ddlLearningStyle');

		if (sLS !== 'ls-1') {
			document.getElementById('chkLearningStyle').checked = true;
		}
		else {
			document.getElementById('chkLearningStyle').checked = false;
		}
	}
	
	function RecalculateAllEmployerRatings()
    {
        alert(AdminToolsControl.FireRecalcEmployerRatings().value);
    }
    
    function RecalculateEmployersGeolocs(redoAll)
    {
        if(confirm("Are you sure you want to do this.  It might take a while")) {
            alert(AdminToolsControl.FireRecalculateEmployersGeolocs(redoAll).value);
        }
    }
    function RecalculateVacancyGeolocs(redoAll) {
        if (confirm("Are you sure you want to do this.  It might take a while")) {
            alert(AdminToolsControl.FireRecalculateVacancyGeolocs(redoAll).value);
        }
    }
    


    function HandleCollegeChoice(sID, sText, arrExtra)  {
        MyObject('CollegeID').value = sID;
        Place(RegisterStudentControl.GetCourses(sID));	                                        
    }
    
    function DeleteImage(userID, imageID)   {
        if (confirm('Are you sure you wish to delete that image?')) {
            ViewImagePopupControl.DeleteImageItem(userID, imageID);
            BlowUp(userID, imageID);
        }
    }
    
    function DeleteImageAndReload(userID, imageID)
    {
        if (confirm('Are you sure you wish to delete that image?')) {
            ViewImagePopupControl.DeleteImageItem(userID, imageID);
            location.reload();
        }
    }
        
    function BlowUp(userID, imageID)    {
        this.UpdateAjaxSessionTimer();
        Place(ViewImagePopupControl.Blowup(userID, imageID));
    }
    
    function PrintingView(userID, imageID)
    {
        var sURL = ViewImagePopupControl.EncodeImageURL(userID, imageID).value;
        window.open(sURL, "SkillsPassportImageViewer");   
    }
    
    function RebuildMyRefs()
    {
        this.UpdateAjaxSessionTimer();
        var res = JobExtraControl.RebuildReferences();
        Place(res);
    }
    
    function SaveReferenceAndRefresh(userID, imageID , refID)
    {
        ViewImagePopupControl.UpdateReference(refID, Value('refName'));
        Place(ViewImagePopupControl.Blowup(userID, imageID));
    }
    
    function DeleteUserReference(refID)
    {
        if (confirm('Are you sure you wish to delete that reference?'))
        {
            JobExtraControl.DeleteUserReference(refID);
            RebuildMyRefs();
        }
    }
    

  function ToggleProgressPanel()
  {
    if (document.getElementById('uppnl').style.display == 'none')
    {
        document.getElementById('uppnl').style.display = 'block';
        document.getElementById('progessPanel').style.display = 'none';
    }
    else
    {
        document.getElementById('uppnl').style.display = 'none';
        document.getElementById('progessPanel').style.display = 'block';
    }
  }
  
  function OpenSpeechBubble(obj)
{

	var downX = findPosX(obj),
		downY = findPosY(obj);
	
	document.getElementById('SpeechBubble').style.left = downX;
	document.getElementById('SpeechBubble').style.top = downY - 170;

	document.getElementById('SpeechBubble').style.display = '';
	//alert('opening bubble with style ' + document.getElementById('SpeechBubble').style.cssText);
}


function ToggleQualInApp(relqalID, applicID)
{
    $('.open > .spinny').css("display","inline");
    MyApplicationControl.FireToggleQualInApp(relqalID, applicID);
    $('.spinny').css("display","none");
}

function DeleteRelQual(relqalID)
{
    if (confirm('This qualification will be deleted from all your CVs and applications.  Are you sure you want to delete it?.') )
    {
        MyApplicationControl.FireDeleteRelQual(relqalID);
        RebuildMyQuals();
    }
}


function SaveJobAppField(me)
{
    //Start spinny
    $('.open > .spinny').css("display","inline");
    this.UpdateAjaxSessionTimer();
    var fldname = me.id,
        cntrl = MyObject(fldname),
        fieldValue = cntrl.value;
    MyApplicationControl.FireSaveJobAppField(fldname, fieldValue,function (res)
        {
            if (res.value != 'ok')  {
                //validation failed
                alert(res.value);
                cntrl.focus();
            }
             //stop spinny
            $('.spinny').css("display","none");
        }           
    ).value;
}

function SaveJobHistoryField(me)
{
    //Start spinny
    $('.open > .spinny').css("display","inline");
    this.UpdateAjaxSessionTimer();
    var fldname = me.id,
        cntrl = MyObject(fldname),
        fieldValue = cntrl.value,
        parts = fldname.split('_'),
        oid = parts[0];
    fldname = 'p_' + parts[2];
    
    MyApplicationControl.FireSaveJobHistoryField(fldname, fieldValue,oid, function (res)
        {
            if (res.value !== 'ok')
            {
                //validation failed
                alert(res.value);
                cntrl.focus();
            }
             //stop spinny
            $('.spinny').css("display","none");
        }           
    ).value;
   
}

function EnableJobHistorySorting()
{
//    $('#assessed').sortable({ items: ".lineitem",
//                              revert: true, 
//                              containment: 'parent' ,
//                              handle:'.draghandle', 
//                              update: function(e,ui)
//                                    {
//                                        var arr = $('#assessed').sortable("toArray");
//                                        MyApplicationControl.FireSaveHistoryOrder(arr);
//                                    }
//                            });
}

function EnableQualSorting()
{
//    $('#QualificationDisplay').sortable({ items: ".qualline",
//                              handle:'.draghandle',                              
//                              revert: true,
//                              update: SaveApplicationQualsOrder,
//                              containment: 'document',
//                              connectWith : $('#EducationDisplay')
//                               });
//                               
//    $('#EducationDisplay').sortable({ items: ".qualline",
//                              handle:'.draghandle', 
//                              revert: true, 
//                              containment: 'document',
//                              update : SaveApplicationQualsOrder,
//                              connectWith : $('#QualificationDisplay')
//                               });

}

function SaveApplicationQualsOrder(e,ui)
{   
    var arrQ = $('#QualificationDisplay').sortable("toArray");
    var arrE = $('#EducationDisplay').sortable("toArray");
    MyApplicationControl.FireSaveQualsOrder(arrQ,arrE);
}

function AddJobHistory()
{
    $('.open > .spinny').css("display","inline");
    this.UpdateAjaxSessionTimer();
    Place(MyApplicationControl.FireCreateNewJobHistory());
    showHideOnMyPage('assessed','assessedHead');  
    $('.spinny').css("display","none");
    location.href = '#Afterhistory';
    EnableJobHistorySorting();
}

function ToggleHistoryInApp(histID, applicID)
{
    $('.open > .spinny').css("display","inline");
    MyApplicationControl.FireToggleHistoryInApp(histID, applicID);
    $('.spinny').css("display","none");
}

function RebuildJobRef()
{
    $('.open > .spinny').css("display","inline");
    Place(MyApplicationControl.FirRebuildJobHistory());
    showHideOnMyPage('assessed','assessedHead');
    $('.spinny').css("display","none");
    EnableJobHistorySorting();
}

function DeleteJobHistoryImage(refID)
{
    JobExtraControl.DeleteUserReference(refID);
    RebuildJobRef();
}

function DeleteJobHistory(historyID)
{
    if (confirm('Are you certain you wish to delete that job from your history?  If you do delete it, it may affect any applications you have already submitted.'))
    {
        $('.open > .spinny').css("display","inline");
        var res = MyApplicationControl.DeleteJobHistory(historyID);
        if (res.value = "ok")
        {
            Place(MyApplicationControl.FirRebuildJobHistory());
            showHideOnMyPage('assessed','assessedHead');
        }
        else
        {
            alert(res.value);
        }
        $('.spinny').css("display","none");
        EnableJobHistorySorting();
    }
}

function DeleteJobAppProfile(profileID)
{
    if (confirm('Are you certain you wish to delete that profile?'))
    {
        Place(MyJobCentreControl.FireDeleteProfile(profileID));   
    }
       
}

function DeleteJobApplication(appID)
{
    if (confirm('Are you certain you wish to delete that application?'))    {
        
        var res = MyJobCentreControl.FireDeleteApplication(appID);
        location.reload();
//        parts  = res.value.split('|');       
//        document.getElementById(parts[0]).innerHTML = parts[1];
//        document.getElementById(parts[2]).innerHTML = parts[3];  
    }      
}

function CreateNewJobAppProfile(copyFromfProfileID)   {
   $('.open > .spinny').css("display","inline");
   MyJobCentreControl.FireCreateNewJobAppProfile(copyFromfProfileID,ReDirect);             
}

function CreateNewApplication(cntrl, vacancyID) {
    SpinMe(cntrl, "Creating...");
    ReDirect(MyApplicationControl.FireCreateNewApplication(vacancyID));    
}

function CreateNewAppWithProfile(cntrl, vacancyID)  {
    //find the id of the profile they have selected which will be 
    SpinMe(cntrl, "Creating...");
    var profileID = Value('ProfileList');
    ReDirect(MyApplicationControl.FireCreateNewAppWithProfile(vacancyID, profileID));    
}

function CreateProfileFromApp(cntrl)    {
    SpinMe(cntrl, "Saving...");
    alert(MyApplicationControl.FireCreateProfileFromApp().value);
    UnSpinMe(cntrl); 
}    

function SubmitMyApplication(cntrl) {
   
   var msg = IsMyApplicationValid();
   if (confirm(msg))    {   
        SpinMe(cntrl, "Submitting..."); 
        MyApplicationControl.FireSubmitApplication(ReDirect); 
   }
}

function IsMyApplicationValid() {
    var msg = "";
    
    if (Value('p_Address.p_Address1')== '') {
        msg += "\tAddress Line 1 is missing \n";
    }
    if (Value('p_Address.p_Address2')== '') {
        msg += "\tAddress Line 2 is missing \n";
    }
    
    if (Value('p_Address.p_Town')== '') {
        msg += "\tAddress Line 2 is missing \n";
    }
    
    if (Value('p_Address.p_PostCode')== '') {
        msg += "\tPostcode is missing \n";
    }
    
    if (Value('p_DOB')== '')    {
        msg += "\tDate Of Birth is missing \n";
    }
    
    if (Value('p_Address.p_Phone')== '' && Value('p_Address.p_Fax')== '')   {
        msg += "\tNo contact phone number has been entered\n";
    }
    
    if (Value('p_Address.p_Email')== '')    {
        msg += "\tEmail address is missing \n";
    }
    
    if (Value('p_Training')== '')   {
        msg += "\tNo Training information has been entered \n";
    }
    
    if (Value('p_Experience')== '') {
        msg += "\tNo Experience information has been entered \n";
    }
    
    if (Value('p_Passion')== '')    {
        msg += "\tNo Passion information has been entered \n";
    }
    
    if (Value('p_CoverLetter')== '')    {
        msg += "\tThe Cover letter is blank \n";
    }
    
    if (msg != "")  {
        msg = "Before you can submit your application, you may want to correct these validation issues:\n\n" + msg;
        msg += "\nOnce submitted, you may not make any further changes to your application.";
        msg += "\n\nPress OK to submit this application anyway.";
    }
    else    {
      msg += "Once submitted you may not make any further changes to your application.";
      msg += "\n\nPress OK to submit this application.";
    }
    return msg;
}

function SpinMe(cntrl, txt)
{
   try
   {
     $(cntrl).before("<span class=\"spinline \">" + txt + "<img src=\"images/ajax-loader.gif\" /></span>");
     //$(cntrl).css("display","none");
     $(cntrl).hide();
   } 
   catch (ex)
   {
   }     
}

function SpinMeWithClass(cntrl, txt, cssClass)
{
   try
   {
     $(cntrl).before("<span class=\"spinline " + cssClass +"\">" + txt + "<img src=\"images/ajax-loader.gif\" /></span>");
     //$(cntrl).css("display","none");
     $(cntrl).hide();
   } 
   catch (ex)
   {
   }  
}

function UnSpinMe(cntrl)
{
   try
   {
     $(cntrl).prev(".spinline").remove();
     $(cntrl).show();
   }
   catch (ex)
   {
   } 
}

function FireDeleteJobFromCentre(jobid)
{
    if (confirm('Are you certain you wish to delete that job?'))
    {
        Place(EmpJobCentreControl.FireDeleteJob(jobid));
    }  
}

function CloseVacancy(cntrl, vacancyID, action)
{
    SpinMe(cntrl, "...");
    var  canContinue = confirm('Are you sure you wish to ' + action + ' this vacancy?');
    if (canContinue)
    {
        var res = EmpJobCentreControl.FireCloseVacancy(vacancyID);
        parts  = res.value.split('|');       
        document.getElementById(parts[0]).innerHTML = parts[1];
        document.getElementById(parts[2]).innerHTML = parts[3];  
        document.getElementById(parts[4]).innerHTML = parts[5];
        document.getElementById(parts[6]).innerHTML = parts[7];
        document.getElementById(parts[8]).innerHTML = parts[9]; 
        document.getElementById(parts[10]).innerHTML = parts[11];     
    }
    UnSpinMe(cntrl); 
    if (action === "Close")  {
        jQuery('#boxPendHead, #boxPend').removeClass('closed').addClass('open');
    }
 
}

function ViewApplicants(vacID)
{
    location.href="Applicants.aspx?vacid=" + vacID;
}

function AppIsReadOnly()
{
    alert('This application has been sent and is read-only.');
}

function ComingSoon()
{
     alert('This functionality has not quite been implemented yet but it will be coming to you very soon. ');
}


function MakeImageDialogReadOnly()
{
    $("#imageviwerControls").remove();
    $("#imageblowup").html("<p>Click an image on the left for a larger version and to see more options.</p>");
}


function MakeApplicationReadOnly()
{
    $("#EducationDisplay a:not(.Picturelink), #QualificationDisplay a:not(.Picturelink), .lineitem a:not(.HistPictureLink) ").attr("onclick","").attr("href","javascript:AppIsReadOnly();");
    $(".mainBodyWide input, .mainBodyWide textarea").attr("disabled","disabled");
    //$(".mainBodyWide .ukspbutton:last").after("<a onclick='history.back();' class='ukspbutton'>Done - Back To Job Centre</a>")
    $(".mainBodyWide .ukspbutton:not(:last)").remove();
    $("#btnSave, #HelpKey").remove();
    $('#assessed , #QualificationDisplay, #EducationDisplay').sortable("destroy");
    //consider allowing links to view quals
    $("#EducationDisplay .draghandle, #QualificationDisplay .draghandle").remove();
    $("#EducationDisplay dd a, #QualificationDisplay dd a, .ApplicHelp").remove();
    
    $("#EducationDisplay dd, #QualificationDisplay dd").each(
        function(i)
        {
            $(this).replaceWith( $(this).text().replace(/\(\)/g,''));
        }
     );
     $("#EducationDisplay input:not(:checked)").parents('.qualline').remove();
     $("#QualificationDisplay input:not(:checked)").parents('.qualline').remove();
     $(".draghandle img").remove();
     $(".lineitem td:last-child a:last-child").remove();
     
     $("#HistorySection .ukspbutton").remove();
 }

function ShowApplicationAsPDF(cntrl, id)
{
    SpinMe(cntrl, "Creating PDF...");
    MyApplicationControl.FireCreatePDF(id); 
    UnSpinMe(cntrl);
}

function ShowCertificateAsPDF(cntrl, id)
{
    SpinMe(cntrl, "Creating PDF...");
    MyRelevantQualDisplayControl.FireCreatePDFCertificate(id); 
    UnSpinMe(cntrl);
}

function ShowAboutCareerIndustryAsPDF(cntrl, id)
{
    SpinMe(cntrl, "Creating PDF...");
    CareerMapsDisplayControl.FireCreateAboutCareerIndustryPDF(id); 
    UnSpinMe(cntrl);
}

function ShowTalentAsPDF(cntrl, id)
{
    SpinMe(cntrl, "Creating Talent PDF...");
    MyApplicationControl.FireCreateTalentPDF(id); 
    UnSpinMe(cntrl);
}

function ChangeAppStatus( applicantID, newStatus, optionalAjaxControl)
{
    //get open status of all the boxes 
    var openarray = new Array();
    jQuery('.open').each(function (i) 
        {
            openarray.push(this.id)                
        });
    
    if (typeof optionalAjaxControl === 'undefined') {
       Place(ApplicantsControl.FireSetStatus( applicantID, newStatus));
    }
    else    {
       Place(optionalAjaxControl.FireSetStatus( applicantID, newStatus));
    }
    //set status and rebuild the boxes
   
    //set all the open ones back again
    while (openarray.length > 0)    {
        var thisid = openarray.pop();
        $("#" + thisid).removeClass('closed').addClass('open');   
    }
    
    //and redo all the sub-fancy menus!
    $('.btnmenu').clickMenu(); 
}
function ShowBulkPDFs(cntrl, vacancyID, filter)
{
    SpinMe(cntrl, "...");
    ApplicantsControl.FireShowBuildPDFs(vacancyID, filter, function()
    {
      window.open("PageasPDF.aspx?logo=false");
      UnSpinMe(cntrl);
    });
}

function MakeBoxScrollAtSize(id, size)  {
    var lst = document.getElementById(id);
    if (lst.offsetHeight > size)    {
        lst.style.height= size + "px"; 
        lst.style.overflow="auto";       
    }
}

function MakeBoxScrollAtSizeWithReset(id, size) {
    var lst = document.getElementById(id);
    lst.style.height = "auto";
    if (lst.offsetHeight > size || lst.offsetHeight == 0)
    {
         $("#" + id).css("height",size + "px").css("overflow-y", "auto").css("overflow-x", "hidden");
    }
}

function maxsize(cntrl, maxlimit)
{
    if (cntrl.value.length >= maxlimit) {
        cntrl.value = cntrl.value.substring(0, maxlimit);    
    }
}



function AddToJobBasket(cntrl, vacId)   {
    var added = VacancySearchControl.ToggleBasket(vacId);
    
    if (added.value)    {
        cntrl.title = "Remove this vacancy from your Shortlist.";
        cntrl.innerHTML = '<img src="images/uksp/basket_delete.png">';
        $("#infolbl" + vacId).html('Added to Shortlist. View it at your <a href="myjobcentre.aspx" target="_parent">Job Centre</a> ');
    }
    else    {
        cntrl.title = "Add this vacancy to your Shortlist.";
        cntrl.innerHTML = '<img src="images/uksp/basket_add.png">';
        $("#infolbl" + vacId).text('Removed from Shortlist.');
    }
    $("#infowrap" + vacId).css("display","inline");
}

function DeletefromBasket(vacId)    {
    //remove the job from basket then kill the line it was from 
    var dontcare = VacancySearchControl.ToggleBasket(vacId);
    $("#basket_dt_" + vacId ).remove();
    $("#basket_dd_" + vacId ).remove();
    var txt = parseInt($("#basket_count").text()) -1; 
    $("#basket_count").text(txt); 
}

function MakeVacancyLive(cntrl, vacID)  {
    SpinMe(cntrl, "Making Live...");
    
    var  canContinue = confirm('Are you sure you wish to make this vacancy Live?');
    if (canContinue)    {
        alert(EmpJobCentreControl.FireMakeVacancyLive(vacID).value);
        var res = EmpJobCentreControl.FireRebuildVacancyLists(vacID);
        parts  = res.value.split('|');       
        document.getElementById(parts[0]).innerHTML = parts[1];
        document.getElementById(parts[2]).innerHTML = parts[3];  
        document.getElementById(parts[4]).innerHTML = parts[5];
        document.getElementById(parts[6]).innerHTML = parts[7];
        document.getElementById(parts[8]).innerHTML = parts[9]; 
        document.getElementById(parts[10]).innerHTML = parts[11];     
    }
    UnSpinMe(cntrl);
}

function TogglePathwaysList()   {
    var disp = $("#CareerPaths").css("display");
    if (disp === "block")    { 
        //$("#CareerPaths").css("display", "none");
        $("#CareerPaths").slideUp('fast');
        $("#ChangePaths").text("Change...");
    }
    else    {
        $("#CareerPaths").slideDown('fast');
        //$("#CareerPaths").css("display", "block");
        $("#ChangePaths").text("Hide List");
    }
    DoPathwayCount();
}

function RebuildJobTitlesList()
{
    cntrl = document.getElementById("pickJobTitlePanel");
    SpinMe(cntrl, "Looking for Jobs Titles...");
    var pathwayIDs = [];
    $(".PathwayCheckBox:checked").each(function (i) 
    {
        pathwayIDs.push(this.id.substr(4));                
    });
        
    VacancySearchControl.GetJobTitlesByPathway(pathwayIDs, "", function(res)
    {
      Place(res);
      UnSpinMe(cntrl)
    });
}

function AddToMiniList(fromList , toDiv)
{
    //take selected item from fromList append item to toDivs
    var tx = GetSelectedOptionText(fromList),
        vl = GetSelectedOptionValue(fromList);
    if (vl != "0" && $('#' + toDiv + ' #pk_' + vl ).length == 0)    {
        var htm = "<span id='pk_" + vl + "'>" + tx + "<a class='pickedItem' onclick='$(this).parent().remove();'>X</a></span>"; 
        $('#' + toDiv).append(htm).append("&nbsp;");
        
        if ($('#' + toDiv + ' a' ).length == 5) {
            $('#' + toDiv).append("<br/>")
        }
    }
}

function DoPathwayCount()
{
    if (!/getspotted/i.test(window.location) && !/talentsearch/i.test(window.location)) {
        var cnt  = $(".PathwayCheckBox:checked").length;
        if (cnt == 0 || cnt == 15)  {
          $("#WhichPaths").text("Searching     :  All industries ");
        }
        else    {   
          $("#WhichPaths").text("Searching     : " + cnt + " (of 15) Industries ");
        }
        
        $("#pickEmployerPanel").css("display", "none");
        $("#ChangeEmployers").text("Pick...");
        $("#pickJobTitlePanel").css("display", "none");
        $("#ChangeJobTitle").text("Pick...");
       //RebuildJobTitlesList();            
    }
    else {
        var cnt  = $(".PathwayCheckBox:checked").length;
        if (cnt == 0 || cnt == 15)  {
          $("#WhichPaths").text("All industries ");
        }
        else    {
          $("#WhichPaths").text(cnt + " (of 15) Industries ");
        }
        
        $("#pickEmployerPanel").css("display", "none");
        $("#ChangeEmployers").text("Pick...");
        $("#pickJobTitlePanel").css("display", "none");
        $("#ChangeJobTitle").text("Pick...");
        if (!/talentsearch/i.test(window.location))     {
            if ($('#FirstRun').val() != "") {
                SaveTalentIndividualPage($('#WhichPaths')[0], true);
            } 
            else    {
                $('#FirstRun').val("Done First Run");
            }	
    	}
	}
}

function searchEmployerFiltering()  {   
    if ($("#pickEmployerPanel").css("display") == "block")  {
        var pathwayIDs = new Array();
        $(".PathwayCheckBox:checked").each(function (i) {
            pathwayIDs.push(this.id.substr(4));                
        });
        
        Place(VacancySearchControl.GetEmployersByPathway(pathwayIDs, Value("searchTermEmployer")));
    }
    else if (Value("searchTermEmployer").length > 2 )   {
        ToggleEmployerList();
    }
}

function ToggleEmployerList()   {
    var disp = $("#pickEmployerPanel").css("display");
    if (disp == "block")    { 
        $("#pickEmployerPanel").css("display", "none");
        $("#ChangeEmployers").text("Pick...");
    }
    else    {
        $("#pickEmployerPanel").css("display", "block");
        $("#ChangeEmployers").text("Hide");
        //now get the list of employers in the selected pathways
 
        var pathwayIDs = new Array();
        $(".PathwayCheckBox:checked").each(function (i) 
        {
            pathwayIDs.push(this.id.substr(4));                
        });
        
        Place(VacancySearchControl.GetEmployersByPathway(pathwayIDs, Value("searchTermEmployer")));
    }
}

function searchJobListFiltering()
{
    if ($("#pickJobTitlePanel").css("display") == "block")  {
       var pathwayIDs = [];
       $(".PathwayCheckBox:checked").each(function (i) 
        {
            pathwayIDs.push(this.id.substr(4));                
        });
        Place(VacancySearchControl.GetJobTitlesByPathway(pathwayIDs, Value("searchTermTitle")));
    }
    else if (Value("searchTermTitle").length > 2 )
    {
        ToggleJobTitleList();
    }
}

function ToggleJobTitleList()
{
    var disp = $("#pickJobTitlePanel").css("display");
    if (disp == "block")
    { 
        $("#pickJobTitlePanel").css("display", "none");
        $("#ChangeJobTitle").text("Pick...");
    }
    else
    {
        $("#pickJobTitlePanel").css("display", "block");
        $("#ChangeJobTitle").text("Hide");
        //now get the list of employers in the selected pathways
 
        var pathwayIDs = new Array();
        $(".PathwayCheckBox:checked").each(function (i) 
        {
            pathwayIDs.push(this.id.substr(4));                
        });
        Place(VacancySearchControl.GetJobTitlesByPathway(pathwayIDs, Value("searchTermTitle")));
    }
}


function SelectAllPathwayCheckBoxes(chked)
{
    $(".PathwayCheckBox").attr("checked",chked);
    DoPathwayCount();
}

function RebuildJobTitleList()
{
    cntrl = $('#pickJobTitlePanel').get(0);
    
    SpinMe(cntrl, "Looking for Jobs...");


    var pathwayIDs = new Array();
    $(".PathwayCheckBox:checked").each(function (i) 
    {
        pathwayIDs.push(this.id.substr(4));                
    });
    JobSearchControl.GetJobTitlesByPathway(pathwayIDs, function(res)
    {
      Place(res);
      UnSpinMe(cntrl)
    });
  			
    
}

function SelectParticularJobs()
{
    var joblistIDs = new Array();
    $("#pickJobTitleList option:selected").each(function () {
        joblistIDs.push(this.value);
      });
   JobSearchControl.SendListToSession(joblistIDs);  
   location.href = "JobSearchResults.aspx?searchType=fromList";

}

function SaveMyPageField(me)
{
    //Start spinny
    $('.spinny').css("display","inline");
    this.UpdateAjaxSessionTimer();
    var fldname = me.id;
    var cntrl = MyObject(fldname);
    var fieldValue = cntrl.value;
    MyPageControl.FireSaveField(fldname, fieldValue,function (res)
        {
            if (res.value != 'ok')
            {
                //validation failed
                alert(res.value);
                cntrl.focus();
            }
             //stop spinny
            $('.spinny').css("display","none");
        }           
    ).value;
   
}

  
        
function ToggleMenu(menuID)
{
    try
    {
        var disp = $("#" + menuID).css("display");
        if (disp == "block")
        { 
            $("#" + menuID).css("display", "none");
        } 
        else
        {
            $("#" + menuID).css("display", "block");
        }
   }
   catch (EXC)
   {
   }     
}

function ToggleSubMenu(menuID)  {
    try {
       $("#" + menuID + " a").each( function (i)    {
            var disp = this.css("display");
            if (disp == "block")    { 
                this.css("display", "none");
            }   else    {
                this.css("display", "block");
            }
        });
   }    catch (EXC) {   }     
}
        
/*  Postcode Lookup Stuff  */
function LookupPostcode(cntrl)
{
    SpinMe(cntrl, "Finding...");
    $("#fAddress1").attr('disabled', 'disabled');
    $("#fAddress1").removeAttr('style');
    $("#fAddress2").attr('disabled', 'disabled');
    $("#fAddress2").removeAttr('style');
    $("#fTown").attr('disabled', 'disabled');
    $("#fTown").removeAttr('style');
    $("#fCounty").attr('disabled', 'disabled');
    $("#fCounty").removeAttr('style');
    $("#fCountry").attr('disabled', 'disabled');
    $("#fCountry").removeAttr('style');
    
    RegisterNewControl.LookupPostcode($("#fPostcode")[0].value,
        function (res)
        {
            //res will contain the select list for listing all the addresses at that postcode
            $("#addresspicker").css("display","block");
            if (res.value.indexOf('No addresses') !== -1)   {
                $("#fAddress1").removeAttr('disabled');
                $("#fAddress1").css('background-color', '#F8AF42');
                $("#fAddress1").val('');
                $("#fAddress1").change(function()   {
                    $("#fAddress1").removeAttr('style');
                    $("#fAddress1").change(function(){return false;});
                });
                $("#fAddress2").removeAttr('disabled');
                $("#fAddress2").val('');
                $("#fTown").removeAttr('disabled');
                $("#fTown").css('background-color', '#F8AF42');
                $("#fTown").val('');
                $("#fTown").change(function()   {
                    $("#fTown").removeAttr('style');
                    $("#fTown").change(function(){return false;});
                });
                $("#fCounty").removeAttr('disabled');
                $("#fCounty").css('background-color', '#F8AF42');
                $("#fCounty").val('');
                $("#fCounty").change(function()   {
                    $("#fCounty").removeAttr('style');
                    $("#fCounty").change(function(){return false;});
                });
                $("#fCountry").removeAttr('disabled');
                $("#fCountry").css('background-color', '#F8AF42');
                $("#fCountry").val('');
                $("#fCountry").change(function()   {
                    $("#fCountry").removeAttr('style');
                    $("#fCountry").change(function(){return false;});
                });
                UnSpinMe(cntrl);
                alert("Sorry, we are unable to Autofill your address with that postcode.  Please enter your details manually.");
            }   else    {
                Place(res);
            }
            UnSpinMe(cntrl);
        }
    );
}

function BuildAddressLinesFromSelection(cntrl)
{
    $('.requestMessage').remove();

    var id = GetSelectedOptionValue(cntrl);
    if (id === 'Other') {
        $("#fAddress1").removeAttr('disabled');
        $("#fAddress1").css('background-color', '#F8AF42');
        $("#fAddress1").val('');
        $("#fAddress1").change(function()   {
            $("#fAddress1").removeAttr('style');
            $("#fAddress1").change(function(){return false;});
        });
        $("#fAddress2").removeAttr('disabled');
        $("#fAddress2").val('');
        $("#fTown").removeAttr('disabled');
        $("#fTown").css('background-color', '#F8AF42');
        $("#fTown").val('');
        $("#fTown").change(function()   {
            $("#fTown").removeAttr('style');
            $("#fTown").change(function(){return false;});
        });
        $("#fCounty").removeAttr('disabled');
        $("#fCounty").css('background-color', '#F8AF42');
        $("#fCounty").val('');
        $("#fCounty").change(function()   {
            $("#fCounty").removeAttr('style');
            $("#fCounty").change(function(){return false;});
        });
        $("#fCountry").removeAttr('disabled');
        $("#fCountry").css('background-color', '#F8AF42');
        $("#fCountry").val('');
        $("#fCountry").change(function()   {
            $("#fCountry").removeAttr('style');
            $("#fCountry").change(function(){return false;});
        });
        $("#addresspicker").html('<strong>Sorry we could not find the correct address. Please enter your details Manually below.</strong>');
        
    }   else    {
        var fields = RegisterNewControl.LookupAddress(id).value.split(',');
        if (fields.length  == 0)
        {
            alert("Sorry, we are unable to Autofill your address with that postcode.  Please enter your details manually.");
            $("#fAddress1").removeAttr('disabled');
            $("#fAddress1").css('background-color', '#F8AF42');
            $("#fAddress1").val('');
            $("#fAddress1").change(function()   {
                $("#fAddress1").removeAttr('style');
                $("#fAddress1").change(function(){return false;});
            });
            $("#fAddress2").removeAttr('disabled');
            $("#fAddress2").val('');
            $("#fTown").removeAttr('disabled');
            $("#fTown").css('background-color', '#F8AF42');
            $("#fTown").val('');
            $("#fTown").change(function()   {
                $("#fTown").removeAttr('style');
                $("#fTown").change(function(){return false;});
            });
            $("#fCounty").removeAttr('disabled');
            $("#fCounty").css('background-color', '#F8AF42');
            $("#fCounty").val('');
            $("#fCounty").change(function()   {
                $("#fCounty").removeAttr('style');
                $("#fCounty").change(function(){return false;});
            });
            $("#fCountry").removeAttr('disabled');
            $("#fCountry").css('background-color', '#F8AF42');
            $("#fCountry").val('');
            $("#fCountry").change(function()   {
                $("#fCountry").removeAttr('style');
                $("#fCountry").change(function(){return false;});
            });
        }  
        else
        {
            $("#fAddress1")[0].value =  fields[0];
            if (fields[0] === '')   {
                $("#fAddress1").removeAttr('disabled');
                $("#fAddress1").css('background-color', '#F8AF42');
                $("#fAddress1").after('<div class="requestMessage">We could not find the first line of your address. Please enter it manually above.</div>')
                $("#fAddress1").change(function()   {
                    $("#fAddress1").removeAttr('style');
                    $("#fAddress1").nextAll('.requestMessage').remove();
                    $("#fAddress1").change(function(){return false;});
                });
            }
            $("#fAddress2")[0].value =  fields[1];
            $("#fTown")[0].value =  fields[2];
            if (fields[2] === '')   {
                $("#fTown").removeAttr('disabled');
                $("#fTown").css('background-color', '#F8AF42');
                $("#fTown").after('<div class="requestMessage">We could not find your town. Please enter it manually above.</div>')
                $("#fTown").change(function()   {
                    $("#fTown").removeAttr('style');
                    $("#fTown").nextAll('.requestMessage').remove();
                    $("#fTown").change(function(){return false;});
                });
            }
            $("#fCounty")[0].value =  fields[3];
            if (fields[3] === '')   {
                $("#fCounty").removeAttr('disabled');
                $("#fCounty").css('background-color', '#F8AF42');
                $("#fCounty").after('<div class="requestMessage">We could not find your County. Please enter it manually above.</div>')
                $("#fCounty").change(function()   {
                    $("#fCounty").removeAttr('style');
                    $("#fCounty").nextAll('.requestMessage').remove();
                    $("#fCounty").change(function(){return false;});
                });
            }
            $("#fCountry")[0].value=  fields[4];
            if (fields[0] === '')   {
                $("#fCountry").removeAttr('disabled');
                $("#fCountry").css('background-color', '#F8AF42');
                $("#fCountry").after('<div class="requestMessage">We could not find your country. Please enter it manually above.</div>')
                $("#fCountry").change(function()   {
                    $("#fCountry").removeAttr('style');
                    $("#fCountry").nextAll('.requestMessage').remove();
                    $("#fCountry").change(function(){return false;});
                });
            }
        }  
        $("#addresspicker").css("display","none");  
    } 
}        
        
function Reg_ShowColleges(shortver)
{
$("#SectorSection").hide();
 var shortVersion = (shortver == 'short');

 //$("#SectorSection").css("display","none"); 
 //$(".CollegeSections").css("display","block");   
 
 $(".CollegeSections").html(RegisterNewControl.GetPlaceOfEducationHTML($('.radioChoice:checked').val()).value);
 $("#PETSection").hide();
 $(".CollegeSections").show();
 
 var cntrl = $("#CollegeSection")[0];
 
 if ($("#CollegeNameResults")[0].options.length == 0)
 {
    SpinMe(cntrl, "Getting List...");
    RegisterNewControl.GetCollegeList(shortVersion,function(res)
    {
         Place(res);
         UnSpinMe(cntrl);    
         Reg_ShowCourseList(shortver);
    });
 }
}

function Reg_ShowCourseList(shortver)
{
var shortVersion = (shortver == 'short');

    var collID = GetSelectedOptionValue('CollegeNameResults');
    if (collID < 0)
    {
        //$("#CollegeNameNotListed").css("display","block");
        //$("#CourseNameNotListed").css("display","block");
        $("#CollegeNameNotListed").show();
        $("#CourseNameNotListed").show();
    }
    else
    {
        //$("#CollegeNameNotListed").css("display","none");
       // $("#CourseNameNotListed").css("display","none");
        $("#CollegeNameNotListed").hide();
        $("#CourseNameNotListed").hide();
    }
    $("#PETSection").hide();
    var cntrl = $("#CourseNameArea")[0];
    SpinMe(cntrl, "Getting Course List...");
    if ($('.radioChoice:checked').val() === "SchoolStudent")    {
        $('#CourseNameArea').html('<select onchange="Reg_CourseNameChanged()" id="CourseNameResults"><option value="0">Diploma in Hospitality</option><option value="0">Diploma in Travel & Tourism</option><option value="0">Various GCSE\'s</option><option value="-1">A different course</option>');
        Reg_CourseNameChanged();
        UnSpinMe(cntrl);  
    }   else    {
        RegisterNewControl.GetCourseList(collID, shortVersion, function(res)
        {
            Place(res);
            Reg_CourseNameChanged();
            UnSpinMe(cntrl);  
        });
    }
}    
function Reg_CourseNameChanged()
{
    var courseID = GetSelectedOptionValue('CourseNameResults');
    if (courseID < 0)
    {
        $("#CourseNameNotListed").show();
    }
    else
    {
        $("#CourseNameNotListed").hide();
    }
    
}

function Reg_ShowSectors()
{
 $("#SectorSection").show();
 $(".CollegeSections").hide();
 $("#PETSection").hide();
}   

function Reg_ShowPET() {
    
    $("#PETSection").show();
    $(".CollegeSections").hide();        
    $("#SectorSection").hide(); 
    $(".Sections").hide();   
}


function Reg_PetChecked(cntrl, existingCollegeName) {
    if ($(cntrl)[0].checked) {
        $("#petFurtherQuestions").show();
        
        var cntrl = $("#petcollegelist")[0];
        SpinMe(cntrl, "Getting List...");
        RegisterNewControl.GetPETCollegeList(existingCollegeName, function(res) {
            Place(res);
            UnSpinMe(cntrl);
        });
       
    }
    else {
        $("#petFurtherQuestions").hide();        
    }    
}


function Reg_PetCollegeChanged() {
    var collID = GetSelectedOptionValue('PetCollegeNameResults');
    if (collID < 0) {
        $("#PetCollegeNameNotListed").show();
    }
    else {
        $("#PetCollegeNameNotListed").hide();
    }
}




function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
            }
    else return '';
   return txt;
}

function EditBabel(reloadedID )
{
    try
    
    {
        var page = location.pathname;
        var suggests = "";
        if (page.indexOf(".aspx" < 1) && $("#MainForm").length > 0)
        {
            suggests = $("#MainForm").attr("action");
        }
    
        var seltext = getSelText().toString();
        var trimmed = seltext.replace(/^\s+|\s+$/g, '') ; 
        
        //move BabelIds element to bottom of page like firebug does it
        $("#BabelIds").dialog("destroy");
        $("#BabelIds").dialog({ position:[0,10], height:"640", width:"420" ,draggable: true, dialogClass: 'flora'});
        $(".ui-dialog").css("background-color","#E0E0E0")
        var res = HeaderControl.ShowBabelEdit(page, suggests);
        var result = res.value;
	    var listTokens = result.split('|');
	    if (listTokens[0] == '0')
	    {
		    alert(listTokens[1]);
		    $("#BabelIds").dialog("close");
        }
	    else
	    {
		    document.getElementById("BabelIds").innerHTML = result;
	    }
     
        //consider a search using getSelText
       if (typeof reloadedID != 'undefined' && $("#bbl" + reloadedID).length > 0)
       {
            $("#bbl" + reloadedID)[0].scrollIntoView(); 
            $("#bbl" + reloadedID).css("background-color","#5ff");
       }
       else
       {
         

           if (trimmed.length > 2 && $("#BabelIds textarea:contains('" + trimmed + "')").length > 0)
           {
            $("#BabelIds textarea:contains('" + trimmed + "')")[0].scrollIntoView(); 
            $("#BabelIds textarea:contains('" + trimmed + "')").css("background-color","#5ff");
           }
       }
   }
   catch (ERRO)
   {
    alert("Sorry, this page is not set up to support Babel Editing ");
   }
    
 }
 
 function PreviewBabelEdit(bId)
 {
    var srchTxt = $("#bbl" + bId)[0].value;
    
    var page = location.pathname;
    var result = HeaderControl.SetBabel(bId, srchTxt,page).value;
    if (result != "OK")
    {
    alert(result);
    }
    else
    {
    
    //alert('About to replace ' + origBabel + ' with ' + srchTxt);
    window.location.reload();
    
    }
 }
 
 function babelAuthCheck()
 {
    var p = $("#babelUserPwd")[0].value;
    var u = $("#babelUserName")[0].value;
    var result = HeaderControl.BabelAuthCheck(u,p).value;
    alert(result);
    window.location.reload();
 }
 
function RegisterNewEmployer(bType) {

    if (!$("#chkCommit").is(':checked')) {
        alert('You must agree to the Good Employer Commitment in order to register as a Good Employer. ');
        $(".regForm .commitment").css("border-color", "#d35063");
        return;
    }

	if (!CheckTerms()) {
		alert('You must agree with the sites terms and conditions before you can register.');
		return;
	}

    SpinMe(MyObject('registerNewUserButtonWait'), "<strong>Creating Your Account, please wait...</strong>");


	//if (!ValidateNewUserForm())
	//	return;

	// Get details
	var sFirstName = document.getElementById('fYourName').value;
	var sLastName = document.getElementById('fLastName').value;
	var sOrgName = document.getElementById('fOrgName').value;
	var sEmail = document.getElementById('fEmail').value;
	
	var sPassword1 = document.getElementById('fPassword1').value;
	var sPassword2 = document.getElementById('fPassword2').value;
	var bOption = document.getElementById('fOptin').checked;
	var sVoucherCode = Value('fVoucherCode');
	var bOptionEmailPref1 = document.getElementById('fOptinEmaiPref1').checked;
	
	

//all new fields
    var sAddress1 = Value('fAddress1');
    var sAddress2 = Value('fAddress2');
    var sAddress3 = Value('fTown');
    var sAddress4 = Value('fPostcode');
    var sAddress5 = Value('fCounty');
    var sAddress6 = Value('fCountry');

    var sEmployeeCount = Value('fEmployeeCount');
    var sMobile = Value('fMobile');
    var sWebsite = Value('fWebsite');
    var fJobTitle = Value('fJobTitle');

    var pathwayIDs = new Array();
    $(".PathwayCheckBox:checked").each(function (i) 
    {
        pathwayIDs.push(this.id.substr(4));                
    });
//end of new fields

	if (bType)
	    RegisterEmployerControl.RegisterNewEmployerPay(sFirstName, sLastName, sOrgName, sPassword1, sPassword2, bOption, sEmail, sAddress1, sAddress2, sAddress3, sAddress4, sAddress5, sAddress6, sEmployeeCount, sMobile, sWebsite, fJobTitle, bOptionEmailPref1, sVoucherCode, pathwayIDs, CallBack_RegEmployer);
	else
	    RegisterEmployerControl.RegisterNewEmployerNoPay(sFirstName, sLastName, sOrgName, sPassword1, sPassword2, bOption, sEmail, sAddress1, sAddress2, sAddress3, sAddress4, sAddress5, sAddress6, sEmployeeCount, sMobile, sWebsite, fJobTitle, bOptionEmailPref1, sVoucherCode, pathwayIDs, CallBack_RegEmployer);					
}

function CallBack_RegEmployer(res) {
    try {
        var result = res.value;

        if (result == '') return;
        var listTokens = result.split('|')

        if (listTokens[0] == '0') {

            UnSpinMe(MyObject('registerNewUserButtonWait'));
            $('#registerNewUserButtonWait').css("display", "block");
            alert(listTokens[1]);
        }
        else if (listTokens[1].indexOf('Java') > -1) {
            UnSpinMe(MyObject('registerNewUserButtonWait'));
            $('#registerNewUserButtonWait').css("display", "block");
            location.href = listTokens[1];
        }
        else
            location.href = listTokens[1];
    }
    catch (Exc) {
        UnSpinMe(MyObject('registerNewUserButtonWait'));
        $('#registerNewUserButtonWait').css("display", "block");
        alert(Exc.message);
    }
		
}

function VisitForum()
{
    var res = HeaderControl.VisitForum()
    var result = res.value
	var listTokens = result.split('|')
					
	if (listTokens[0] == '0') {
		alert(listTokens[1]);
		this.UpdateAjaxSessionTimer();
	}
	else
		window.open(listTokens[0]);

}



//ie tooltipery

function showIE6Tooltip(maxOptionCount, e){
      if (typeof(document.body.style.maxHeight) != 'undefined') {
        return;
      }
        if(!e){var e = window.event;}
        var obj = e.srcElement;
        var objHeight = obj.offsetHeight;
        var optionCount = obj.options.length;
        var eX = e.offsetX;
        var eY = e.offsetY;

        //vertical position within select will roughly give the moused over option...
        var hoverOptionIndex = Math.floor(eY / (objHeight / maxOptionCount));

  if(hoverOptionIndex >= 0 && hoverOptionIndex < obj.options.length && obj.options[hoverOptionIndex].title.length != 0) {
       
          var tooltip = document.getElementById('dvDiv');
          tooltip.innerHTML = obj.options[hoverOptionIndex].title;
         

    mouseX=e.pageX?e.pageX:e.clientX;
    mouseY=e.pageY?e.pageY:e.clientY;
  
    tooltip.style.left=mouseX+10;
    tooltip.style.top=mouseY;
 
    tooltip.style.display = 'block';
   
    var frm = document.getElementById('frm');
    frm.style.left = tooltip.style.left;
    frm.style.top = tooltip.style.top;
    frm.style.height = tooltip.offsetHeight;
    frm.style.width = tooltip.offsetWidth;
    frm.style.display = 'block';
  } else {
    hideIE6Tooltip(e);
  }
    }


    function hideIE6Tooltip(e){
        var tooltip = document.getElementById('dvDiv');
        var iFrm = document.getElementById('frm');
        try{
        tooltip.innerHTML = '';
        tooltip.style.display = 'none';
        iFrm.style.display = 'none';} catch (bang) {}
    }
    
    function ToggleMiniMyPage() 
    { 
		$("#miniMyPage").toggle();
        if ($("#miniMyPage").css("display") == "none")
        {
           setCookie('HideMyPage','true', 365);
           setCookie('MiniMyPageLocation','47px:-170px'); //reset the last location
           $("a .textOverlay").text("Show Mini My Page");
        }
        else
        {
           setCookie('HideMyPage','false', 365);
           $("a .textOverlay").text("Hide Mini My Page")
        }
        
	}
	
	function RecordMiniMyPos(e, ui)
	{
	    var top = $("#miniMyPage").css("top");
	    var lft = $("#miniMyPage").css("left");
	    setCookie('MiniMyPageLocation',top + ':' + lft, 365); //reset the last location
	}

    
    
     function setCookie(name, value, expires, path, domain, secure)
     {
	    var today = new Date();
        today.setTime(today.getTime());

        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }

        var expires_date = new Date(today.getTime() + (expires));
    	
        document.cookie = name+"="+escape(value) +
            ((expires) ? ";expires="+expires_date.toGMTString() : "") + 
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ((secure) ? ";secure" : "");
    }
    
    
   function FixMyskillsTick()
   {
     var txt = $("#MySkillsBox textarea")[0].value;
     if (txt.length > 0)
     {
        $("#MySkillsBox").addClass("done");
        $("#MySkillsTick").removeClass("notdone").addClass("done");
        
     }
     else
     {
        $("#MySkillsBox").removeClass("done");
         $("#MySkillsTick").removeClass("done").addClass("notdone");
     }
   }
   
   function UpdateProviderRating(rdoButton, questionID, collegeID)
   {
      
       SpinMeWithClass($("#youranswer")[0], "Saving...", "text");
      
       QualCourseControl.UpdateProviderRating(rdoButton.value, questionID, collegeID, function (res) 
        {
        
          Place(res);
          UnSpinMe($("#youranswer")[0]);
        }
       );
   }

   function UpdateCourseRating(rdoButton, questionID, courseID)
   {
      
       SpinMeWithClass($("#youranswer")[0], "Saving...", "text");
      
       CourseInfoControl.UpdateCourseRating(rdoButton.value, questionID, courseID, function (res) 
        {
        
          Place(res);
          UnSpinMe($("#youranswer")[0]);
        }
       );
   }


function AddWatermark(selector, prompt)
{
        
        $(selector).addClass("watermarkOn")
        if ($(selector).val() == "" || $(selector).val() == prompt)
          $(selector).val(prompt);
        else
          $(selector).removeClass("watermarkOn")
        
        $(selector).focus(function() {

            $(this).filter(function() {

                return $(this).val() == "" || $(this).val() == prompt

            }).removeClass("watermarkOn").val("");

        });

        $(selector).blur(function() {
            $(this).filter(function() {
                return $(this).val() == ""
            }).addClass("watermarkOn").val(prompt);

        });
                       
}


function ShowFullString(elm, st)
{
    $(elm).replaceWith(st);
}

function ToggleJFQ( qID, fieldname, jobcatID)
{
   
          
    AdminJobQualFilterControl.FireToggleJobQualFilter(qID, fieldname,jobcatID, function (res) 
        {
         
        });
        
}

function RebuildJQFList()
{
    SpinMe($("#qualsList")[0], "Looking...");
    AdminJobQualFilterControl.FireRebuildJQFList(GetSelectedOptionValue('joblist'), function (res)
        {
            Place(res);
            UnSpinMe($("#qualsList")[0]);
        });
}

function QuickSetCurrentJobNPath(jobid, cntrlID)
{
    var pathOID = GetSelectedOptionValue(cntrlID);
    QuickSetCurrentJob(jobid, pathOID);
    
    
}

function QuickSetCurrentJob(jobid, pathid)
{
   // alert(jobid + " : " + pathid );
    var res =  AdminEmployerJobPopupControl.FireSetCurrentJob(jobid, pathid);
    alert(res.value);
}








    
//    if (sFlagFilter == "") //show all rows
//    {
//        $(".provListWide tr").each(  function () { $(this).show(); }  );
//    }
//    else
//    {
//    
//        //hide all rows first 
//        $(".provListWide tr").each( function (){  $(this).hide(); } );
//        //show hearder
//        $(".provListWide tr:first").show();   
//        //then show the ones that match the filter 
//        var selectr = ".provListWide img.flag[src=images/" + sFlagFilter + "]"
//        $(selectr).each(function () { $(this.parentElement.parentElement).show();}  );
//    }
//}
 function ShowSavingText(WhatsBeenClicked)    {
        $('.DestroyMe').remove();
        $('.SavingText').remove();
        $(WhatsBeenClicked).parent().parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" />  Saving...</span>');
        if(typeof $(WhatsBeenClicked).parent().parent().siblings('td:first')[0] === "undefined")   {
            $(WhatsBeenClicked).parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" />  Saving...</span>');
        }
        $('.SavingText').show();
   }
   
   function validateEmail( strValue) {
    var objRegExp  =/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

      //check for valid email
      return objRegExp.test(strValue);
    }
   
    function SaveTalentIndividualPage(WhatsBeenClicked, bAutoMessage) {
        //Show that we are saving!
        var bSetActiveTo = $('#Active').is(':checked'),
            bShowToAll = $('#bShowToAll').is(':checked');
        
        if(bAutoMessage)    {
            ShowSavingText(WhatsBeenClicked);
        } else {
            if (bSetActiveTo)   {
                bSetActiveTo = false;
                $('#ActivationStateMsg').html('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Removing Listing...</span>');
                $('#ActivationStateMsg').fadeIn('fast');
                
            } else {
                bSetActiveTo = true;
                $('#ActivationStateMsg').html('<span class="SavingText" style="color:green;" ><img src="images/ajax-loader.gif" /> Listing...</span>');
                $('#ActivationStateMsg').fadeIn('fast');
            }
        }
        //$('.SavingText').show('fast');
        //alert('Im Trying');
        
        //Data Harvest Supreme!
        var bPermFullTime       = $('#PermFullTime').is(':checked'),
            bPermPartTime       = $('#PermPartTime').is(':checked'),
            bTempFullTime       = $('#TempFullTime').is(':checked'),
            bTempPartTime       = $('#TempPartTime').is(':checked'),
            bApprenticeship     = $('#Apprenticeship').is(':checked'),
            bNVQLvl2            = $('#NVQLvl2').is(':checked'),
            bNVQLvl3            = $('#NVQLvl3').is(':checked'),
            sTalentLocation     = $('#TalentLocation').val(),
            iXMilesOf           = $('#xMilesOf').val(),
            sPostCode           = $('#TalentPostCode').val(),
            iProfileOID         = $('#ProfileList').val(),
            iSalaryType         = $('#SalaryType').val(),
            dTempTermFrom       = $('#TempFrom').val(),
            dTempTermTo         = $('#TempTo').val(),
            sSalaryRange        = null,
            sContactEmail       = $('#ContactEmail').val(),
            sProfileName       = $('#ProfileName').val(),
            sTalentOID       = $('#TalentOID').val(),
            sWordSellMe       = $('#WordSell').val();
            
            if (iProfileOID !== "-1" || iProfileOID != "0") {
                $('.ProEditLink').hide();
                $('#ProEdit' + iProfileOID).show();
            }
            
            if (sContactEmail !== "" && !validateEmail(sContactEmail))  {
                $('.SavingText').remove();
                $('.DestroyMe').remove();
                $('#ContactEmail').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                if(typeof $('#ContactEmail').parent().parent().siblings('td:first')[0] === "undefined")   {
                    $('#ContactEmail').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                }
                $('.SavingText').html('<br /> Is Not A Valid Email').
			    css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                $('#ContactEmail')[0].focus();
                return false;
            }
            
            switch (iSalaryType) {
                case "0":
                    sSalaryRange = $('#Salary_0 :selected').text();
                    break;
                case "1":
                    sSalaryRange = $('#Salary_1 :selected').text();
                    break;
                case "2":
                    sSalaryRange = $('#Salary_2 :selected').text();
                    break;
                case "3":
                    sSalaryRange = $('#Salary_3').val();
					break;
                case "-1":
                    sSalaryRange = "-1";
            }
            
            var pathwayIDs = [];
                $(".PathwayCheckBox:checked").each(function (i) 
                {
                    pathwayIDs.push(this.id.substr(4));                
                });
                
            if (bApprenticeship && !$('#AprentishipExtra').is(':visible'))   {
                $('.AprentishipExtra').fadeIn('slow');       
            } else  {
                $('.AprentishipExtra').fadeOut('slow');
                if(bNVQLvl2)    {
                    $('#NVQLvl2').attr('checked', false);
                    bNVQLvl2 = false;
                }        
                if(bNVQLvl3)    {
                    $('#NVQLvl3').attr('checked', false);
                    bNVQLvl3 = false;
                }
            }
            if($(WhatsBeenClicked).is(':checked'))  {
                $('.NVQBoxes').each(function()  {
                    if (this !== WhatsBeenClicked)  {
                        $(this).attr('checked', false);
                        if ($(this).attr('id') === "NVQLvl2")   {
                            bNVQLvl2 = false;
                        } else  {
                            bNVQLvl3 = false;
                        }
                    }
                });
            }
           
            if  (bTempFullTime || bTempPartTime)    {
                $('.TempTermRow').fadeIn('slow');
            } else  {
                $('.TempTermRow').fadeOut('slow');
            }
            
            var myDateRegEx = /^[0123]?[0-9]\/[01]?[0-9]\/[012][0-9][0-9][0-9](\s[012][0-9]:[0-6][0-9]:[0-6][0-9])?$/;
                        
            if (!myDateRegEx.test(dTempTermFrom) && dTempTermFrom !== "")    {
                    $('.SavingText').remove();
                    $('.DestroyMe').remove();
                    $('#TempTermLatch').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                    if(typeof $('#TempTermLatch').parent().parent().siblings('td:first')[0] === "undefined")   {
                        $('#TempTermLatch').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                    }
                    $('.SavingText').html('<br /> ' + dTempTermFrom + ' Is Not A Valid Date').
				    css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                    $('#TempFrom')[0].focus();
                    return false;
            }
            
            if (!myDateRegEx.test(dTempTermTo) && dTempTermTo !== "")    {
                    $('.SavingText').remove();
                    $('.DestroyMe').remove();
                    $('#TempTermLatch').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                    if(typeof $('#TempTermLatch').parent().parent().siblings('td:first')[0] === "undefined")   {
                        $('#TempTermLatch').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                    }
                    $('.SavingText').html('<br /> ' + dTempTermTo + ' Is Not A Valid Date').
				    css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                    $('#TempTo')[0].focus();
                    return false;
            }
            
            var myRegEx = new RegExp('^[a-zA-Z]{1,2}[0-9]{1,2}\\s?[0-9]{1}[a-zA-Z]{2}$', '');
            
            if (!myRegEx.test(sPostCode) && sPostCode !== "")    {
                    $('.SavingText').remove();
                    $('.DestroyMe').remove();
                    $('#TalentPostCode').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                    if(typeof $('#TalentPostCode').parent().parent().siblings('td:first')[0] === "undefined")   {
                        $('#TalentPostCode').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                    }
                    $('.SavingText').html(' Postcode is invalid').
				    css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                    $('#TalentPostCode')[0].focus();
                    return false;
            }
            var sReason = "";
            
            switch ($('#ReasonDD').val()) {
            case "-1":
                sReason = "";
                break;
            case "0":
                sReason = $('#ReasonDD :selected').text();
                break;
            case "1":
                sReason = $('#DeActivationReasonOther').val();
			}
            
            if (bSetActiveTo) {
                if (confirm($('#ActivateWarningText').val()))  {
                    if (!bPermFullTime && !bPermPartTime && !bTempFullTime && !bTempPartTime && !bApprenticeship)   {
                        $('.SavingText').html('Not Saved <br /> You must be looking for atleast<br /> one type of work if you are listed!');
                        $('.SavingText').css('color','red');
                        $('#ActivationStateMsg').html('<span style="color:red;" class="SavingText">You must be looking for atleast 1 type of work (Temp, Perm, Apprenticeship)</span>');
                        $('#ActivationStateMsg').fadeIn('slow');
                        return false;
                    }
                    
                    if (sContactEmail === "")    {
                        $('.SavingText').html('Not Saved <br /> Contact Email is <br /> Required Field for active Talent');
                        $('.SavingText').css('color','red');
                        $('#ActivationStateMsg').html('<span style="color:red;" class="SavingText">You must have specified a valid contact email to be listed</span>');
                        $('#ActivationStateMsg').fadeIn('slow');
                        $('#ContactEmail').get(0).focus();
                        return false;
                    }
                }
                else
                {
                    $('.SavingText').html('');
                    return false;
                }
            }
            
        GetSpottedControl.SaveTalentProfile(bPermFullTime, bPermPartTime, bTempFullTime, bTempPartTime, bApprenticeship, bNVQLvl2, bNVQLvl3, sTalentLocation, iXMilesOf, sPostCode, iProfileOID, iSalaryType, sSalaryRange, pathwayIDs, dTempTermFrom, dTempTermTo, bSetActiveTo, sReason, bShowToAll, sWordSellMe, sContactEmail, sTalentOID, sProfileName, function(sReturn)    { 
            //var sReturn = GetSpottedControl.SaveTalentProfileTest();
            var sResult = sReturn.value;
            var Response = sResult.split('|');
            if (Response[0] == 1)  {
                $('.SavingText').html('<!--<img src="images/ajax-loader.gif" />-->&nbsp;&nbsp;&nbsp;&nbsp; ' + Response[1]);
                $('.SavingText').css('font-weight', 'normal');
                if (bAutoMessage)   {                
                    $('.SavingText').fadeOut('slow', function() {
                        $('.SavingText').remove();
                        $('.DestroyMe').remove();
                    });
                } else {
                    $('#Active').attr('checked', bSetActiveTo);
                    $('#ActivationStateMsg').fadeOut('slow', function() {
                       if(!bSetActiveTo) {
                            $('#DeActivate1, #DeActivate2, #ReasonOther, #DeActivate3').fadeOut('fast');
                            $('#Activate').fadeIn('slow');
                       } else {
                            window.location = "MyJobCentre.aspx";
                            $('#Activate').fadeOut('fast');
                            $('#DeActivate1').fadeIn('slow');
                            $('#ReasonDD').get(0).selectedIndex = 0;
                            $('#DeActivationReasonOther').val('');
                       }
                    });
                }
            } else if(Response[0] == 2)    {
                window.location = Response[1];
            }else {
                $('.SavingText').html(Response[1]).
				css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
				
            }
        });
    }
    
    function CheckReasonDD()    {
        switch ($('#ReasonDD').val()) {
            case "-1":
                $('#ReasonOther').fadeOut('slow');
                $('#DeActivate3').fadeOut('slow');
                break;
            case "0":
                $('#ReasonOther').fadeOut('slow');
                $('#DeActivate3').fadeIn('slow');
                break;
            case "1":
                if ($('#DeActivationReasonOther').val() !== "")  {
                    $('#ReasonOther').fadeIn('slow');
                    $('#DeActivate3').fadeIn('slow');
                } else  {
                    $('#DeActivate3').fadeOut('slow');
                    $('#ReasonOther').fadeIn('slow');
                }
                break;
        }
    }
    
       function ShowCheckText(WhatsBeenClicked)    {
        $('.DestroyMe').remove();
        $('.SavingText').remove();
        $(WhatsBeenClicked).parent().parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" />  Checking...</span>');
        if(typeof $(WhatsBeenClicked).parent().parent().siblings('td:first')[0] === "undefined")   {
            $(WhatsBeenClicked).parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" />  Checking...</span>');
        }
        $('.SavingText').show();
   }
    
    function CheckTalentSearchValues(WhatsBeenClicked, bAutoMessage) {
        //Show that we are saving!
        if(bAutoMessage)    {
            ShowCheckText(WhatsBeenClicked);
        } else {
            bSetActiveTo = false;
            $('#ActivationStateMsg').html('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Removing Listing...</span>');
            $('#ActivationStateMsg').fadeIn('fast');
        }
        
        //Data Harvest Supreme!
        var bPermFullTime       = $('#PermFullTime').is(':checked'),
            bPermPartTime       = $('#PermPartTime').is(':checked'),
            bTempFullTime       = $('#TempFullTime').is(':checked'),
            bTempPartTime       = $('#TempPartTime').is(':checked'),
            bApprenticeship     = $('#Apprenticeship').is(':checked'),
            bNVQLvl2            = $('#NVQLvl2').is(':checked'),
            bNVQLvl3            = $('#NVQLvl3').is(':checked'),
            sTalentLocation     = $('#TalentLocation').val(),
            iXMilesOf           = $('#xMilesOf').val(),
            sPostCode           = $('#TalentPostCode').val(),
            iSalaryType         = $('#SalaryType').val(),
            dTempTermFrom       = $('#TempFrom').val(),
            dTempTermTo         = $('#TempTo').val(),
            sSalaryRange        = null;
            
            switch (iSalaryType) {
                case "0":
                    sSalaryRange = $('#Salary_0 :selected').text();
                    break;
                case "1":
                    sSalaryRange = $('#Salary_1 :selected').text();
                    break;
                case "2":
                    sSalaryRange = $('#Salary_2 :selected').text();
                    break;
                case "3":
                    sSalaryRange = $('#Salary_3').val();
					break;
                case "-1":
                    sSalaryRange = -1;
                    break;
                    
            }
            
            if (bApprenticeship && !$('#AprentishipExtra').is(':visible'))   {
                $('.AprentishipExtra').fadeIn('slow');
            } else  {
                $('.AprentishipExtra').fadeOut('slow');
                if(bNVQLvl2)    {
                    $('#NVQLvl2').attr('checked', false);
                    bNVQLvl2 = false;
                }        
                if(bNVQLvl3)    {
                    $('#NVQLvl3').attr('checked', false);
                    bNVQLvl3 = false;
                }
            }
            if($(WhatsBeenClicked).is(':checked'))  {
                $('.NVQBoxes').each(function()  {
                    if (this !== WhatsBeenClicked)  {
                        $(this).attr('checked', false);
                        if ($(this).attr('id') === "NVQLvl2")   {
                            bNVQLvl2 = false;
                        } else  {
                            bNVQLvl3 = false;
                        }
                    }
                });
            }
           
            if  (bTempFullTime || bTempPartTime)    {
                $('.TempTermRow').fadeIn('slow');
            } else  {
                $('.TempTermRow').fadeOut('slow');
            }
            
            var myDateRegEx = /^[0123]?[0-9]\/[01]?[0-9]\/[012][0-9][0-9][0-9](\s[012][0-9]:[0-6][0-9]:[0-6][0-9])?$/;
                        
            if (!myDateRegEx.test(dTempTermFrom) && dTempTermFrom !== "")    {
                    $('.SavingText').remove();
                    $('.DestroyMe').remove();
                    $('#TempTermLatch').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                    if(typeof $('#TempTermLatch').parent().parent().siblings('td:first')[0] === "undefined")   {
                        $('#TempTermLatch').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                    }
                    $('.SavingText').html('<br /> ' + dTempTermFrom + ' Is Not A Valid Date').
				    css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                    $('#TempFrom')[0].focus();
                    return false;
            }
            
            if (!myDateRegEx.test(dTempTermTo) && dTempTermTo !== "")    {
                    $('.SavingText').remove();
                    $('.DestroyMe').remove();
                    $('#TempTermLatch').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                    if(typeof $('#TempTermLatch').parent().parent().siblings('td:first')[0] === "undefined")   {
                        $('#TempTermLatch').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                    }
                    $('.SavingText').html('<br /> ' + dTempTermTo + ' Is Not A Valid Date').
				    css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                    $('#TempTo')[0].focus();
                    return false;
            }
            
            var myRegEx = new RegExp('^[a-zA-Z]{1,2}[0-9]{1,2}\\s?[0-9]{1}[a-zA-Z]{2}$', '');
            
            if (!myRegEx.test(sPostCode) && sPostCode !== "")    {
                    $('.SavingText').remove();
                    $('.DestroyMe').remove();
                    $('#TalentPostCode').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                    if(typeof $('#TalentPostCode').parent().parent().siblings('td:first')[0] === "undefined")   {
                        $('#TalentPostCode').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                    }
                    $('.SavingText').html(' Postcode is invalid').
				    css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                    $('#TalentPostCode')[0].focus();
                    return false;
            }
            
        TalentSearchControl.CheckTempDates(dTempTermFrom, dTempTermTo, function(sReturn)    { 
            //var sReturn = TalentSearchControl.SaveTalentProfileTest();
            var sResult = sReturn.value;
            var Response = sResult.split('|');
            if (Response[0] == 1)  {
                $('.SavingText').html('<!--<img src="images/ajax-loader.gif" />-->&nbsp;&nbsp;&nbsp;&nbsp; Done!');
                $('.SavingText').css('font-weight', 'normal');
                $('.SavingText').fadeOut('slow', function() {
                    $('.SavingText').remove();
                    $('.DestroyMe').remove();
                });
            } else if(Response[0] == 2)    {
                window.location = Response[1];
            }else {
                $('.SavingText').html(Response[1]).
				css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
				
            }
        });
    }
    
        function SearchTalent(WhatsBeenClicked, bAutoMessage) {
        //Show that we are saving!
        $('#SearchMsg').html('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Searching Talent...</span>');
        $('#SearchMsg').fadeIn('fast');
        //Data Harvest Supreme!
        var bPermFullTime       = $('#PermFullTime').is(':checked'),
            bPermPartTime       = $('#PermPartTime').is(':checked'),
            bTempFullTime       = $('#TempFullTime').is(':checked'),
            bTempPartTime       = $('#TempPartTime').is(':checked'),
            bApprenticeship     = $('#Apprenticeship').is(':checked'),
            bNVQLvl2            = $('#NVQLvl2').is(':checked'),
            bNVQLvl3            = $('#NVQLvl3').is(':checked'),
            sTalentLocation     = $('#TalentLocation').val(),
            iXMilesOf           = $('#xMilesOf').val(),
            sPostCode           = $('#TalentPostCode').val(),
            iProfileOID         = $('#ProfileList').val(),
            iSalaryType         = $('#SalaryType').val(),
            dTempTermFrom       = $('#TempFrom').val(),
            dTempTermTo = $('#TempTo').val(),
            bPreEmpTrain = $('#PreEmployTrain').is(':checked'),
            sSalaryRange        = null;
            
        switch (iSalaryType) {
            case "0":
                sSalaryRange = $('#Salary_0 :selected').text();
                break;
            case "1":
                sSalaryRange = $('#Salary_1 :selected').text();
                break;
            case "2":
                sSalaryRange = $('#Salary_2 :selected').text();
                break;
            case "3":
                sSalaryRange = $('#Salary_3').val();
			    break;
            case "-1":
                sSalaryRange = -1;
                break;
        }
        
        var JobOIDs = [],
            JobTitles = [];
            $("#JobTitles div.SuggestedJobItem").each(function (i) 
            {
                JobTitles.push($('span.JobTitle' ,this).text());
                JobOIDs.push($(this).attr('OID'));
            });
        
        var pathwayIDs = [];
            $(".PathwayCheckBox:checked").each(function (i) 
            {
                pathwayIDs.push(this.id.substr(4));                
            });
            
        if (bApprenticeship && !$('#AprentishipExtra').is(':visible'))   {
            $('.AprentishipExtra').fadeIn('slow');       
        } else  {
            $('.AprentishipExtra').fadeOut('slow');
            if(bNVQLvl2)    {
                $('#NVQLvl2').attr('checked', false);
                bNVQLvl2 = false;
            }        
            if(bNVQLvl3)    {
                $('#NVQLvl3').attr('checked', false);
                bNVQLvl3 = false;
            }
        }
        if($(WhatsBeenClicked).is(':checked'))  {
            $('.NVQBoxes').each(function()  {
                if (this !== WhatsBeenClicked)  {
                    $(this).attr('checked', false);
                    if ($(this).attr('id') === "NVQLvl2")   {
                        bNVQLvl2 = false;
                    } else  {
                        bNVQLvl3 = false;
                    }
                }
            });
        }
       
        if  (bTempFullTime || bTempPartTime)    {
            $('.TempTermRow').fadeIn('slow');
        } else  {
            $('.TempTermRow').fadeOut('slow');
        }
        
        var myDateRegEx = /^[0123]?[0-9]\/[01]?[0-9]\/[012][0-9][0-9][0-9](\s[012][0-9]:[0-6][0-9]:[0-6][0-9])?$/;
                    
        if (!myDateRegEx.test(dTempTermFrom) && dTempTermFrom !== "")    {
                $('.SavingText').remove();
                $('.DestroyMe').remove();
                $('#TempTermLatch').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                if(typeof $('#TempTermLatch').parent().parent().siblings('td:first')[0] === "undefined")   {
                    $('#TempTermLatch').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                }
                $('.SavingText').html('<br /> ' + dTempTermFrom + ' Is Not A Valid Date').
		        css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                $('#TempFrom')[0].focus();
                return false;
        }
        
        if (!myDateRegEx.test(dTempTermTo) && dTempTermTo !== "")    {
                $('.SavingText').remove();
                $('.DestroyMe').remove();
                $('#TempTermLatch').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                if(typeof $('#TempTermLatch').parent().parent().siblings('td:first')[0] === "undefined")   {
                    $('#TempTermLatch').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                }
                $('.SavingText').html('<br /> ' + dTempTermTo + ' Is Not A Valid Date').
		        css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                $('#TempTo')[0].focus();
                return false;
        }
        
        var myRegEx = new RegExp('^[a-zA-Z]{1,2}[0-9]{1,2}\\s?[0-9]{1}[a-zA-Z]{2}$', '');
        
        if (!myRegEx.test(sPostCode) && sPostCode !== "")    {
                $('.SavingText').remove();
                $('.DestroyMe').remove();
                $('#TalentPostCode').parent().parent().siblings('td:first').append('<span class="SavingText" style="display:inline;"><img src="images/ajax-loader.gif" /> Saving...</span>');
                if(typeof $('#TalentPostCode').parent().parent().siblings('td:first')[0] === "undefined")   {
                    $('#TalentPostCode').parent().siblings('td:first').append('<span class="SavingText" ><img src="images/ajax-loader.gif" /> Saving...</span>');
                }
                $('.SavingText').html(' Postcode is invalid').
		        css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
                
                $('#TalentPostCode')[0].focus();
                return false;
        }
        
        if (!bPermFullTime && !bPermPartTime && !bTempFullTime && !bTempPartTime && !bApprenticeship)   {
            bPermFullTime = bPermPartTime  = bTempFullTime = bTempPartTime = bApprenticeship = true;
        }
            
        TalentSearchControl.SearchForTalent(bPermFullTime, bPermPartTime, bTempFullTime, bTempPartTime, bApprenticeship, bNVQLvl2, bNVQLvl3, sTalentLocation, iXMilesOf, sPostCode, iSalaryType, sSalaryRange, pathwayIDs, dTempTermFrom, dTempTermTo, JobOIDs, JobTitles, bPreEmpTrain, function(sReturn)    { 
            var sResult = sReturn.value;
            var Response = sResult.split('|');
            if (Response[0] == 1)  {
                $('.SavingText').html('<!--<img src="images/ajax-loader.gif" />-->&nbsp;&nbsp;&nbsp;&nbsp; Search Complete');
                $('.SavingText').css({'font-weight':'normal','color':'green'});
                $('#SearchMsg').fadeOut('slow');
                $('#ResultsCount').html(Response[1]);
                $('#TalentResults').html(Response[2]);
                $('#TalentPageNumbers').html(Response[3]);
            }else {
                $('.SavingText').html(Response[1]).
				css({"color":"red","font-weight":"bold","possition":"relative","top":"0px"});
            }
        });
    }
    
    function ChangeTalentSearchPage(PageNumber)  {
        TalentSearchControl.ChangeTalentPage(PageNumber, function(sReturn)    { 
            var sResult = sReturn.value;
            var Response = sResult.split('|');
            if (Response[0] == 1)  {
                $('#TalentResults').html(Response[1]);
                $('#TalentPageNumbers').html(Response[2]);
            }
            else
            {
                alert(Response[1]);
            }
        });
    }

    function GetArgs() {
       var args = {},
           query = location.search.substring(1),
           pairs = query.split('&');
       for(i=0; i < pairs.length; i++) {
           var pos = pairs[i].indexOf('=');
           if (pos === -1)	{ continue; }
           var argname = pairs[i].substring(0,pos);
           var value = pairs[i].substring(pos+1);
           args[argname] = unescape(value);
       }

       return args;
   }
   
    function GoBackWithNewQueryStringValues()   {
        if (location.search.indexOf('ReturnQuery') === -1)  {
            try
            {
            window.location = document.referrer;
            }
            catch (excp)
            {
                history.back(1);
            }
            return false;
        }
    
        var qStringValues = GetArgs().ReturnQuery,
            QuesryStringValues = '',
            iCount = 1;
            
        if (qStringValues.indexOf(';') === -1)  {
            var qStringIdAndValueSingle = qStringValues.split(':');
            QuesryStringValues = qStringIdAndValueSingle[0] + '=' + qStringIdAndValueSingle[1];
        }   else    {
            for (i=0; i < qStringValues.split(';').length; i++) {
                var qStringIdAndValue = qStringValues.split(';')[i].split(':');
                QuesryStringValues = QuesryStringValues + qStringIdAndValue[0] + '=' + qStringIdAndValue[1];
                if (iCount !== qStringValues.split(';').length)   {
                    QuesryStringValues = QuesryStringValues + "&";
                }
                iCount++;
            }
        }
        
        if (document.referrer.indexOf('?') === -1)  {
            window.location = document.referrer + '?' + QuesryStringValues;
        } else  {
            var ReferrerMinusQuery = document.referrer.substring(0,document.referrer.indexOf('?'));
            window.location = ReferrerMinusQuery + '?' + QuesryStringValues;
        }
    }
 
   function SetPersonalDetailsViewingStatus(TalentOid)   {
        $('#PersonalDetailsStatus').html('<img src="images/ajax-loader.gif" /> Changing Status...');
        MyApplicationControl.ChangeTalentPersonalDetailsViewStatus(TalentOid, function(res) {
            var resSplit = res.value.split('|');
            if (resSplit[0] === "1")    {
                $('#PersonalDetailsStatus').html(resSplit[1]).css({'color':'green'});
            } else {
                $('#PersonalDetailsStatus').html(resSplit[1]).css({'color':'red','font-weight':'bold'});
            }
        });
   }
   
   function SubmitContactDeclineReason(sContactRequestOID)    {
        var sReason = $('#ContactDeclineReason :selected').text();
        
        $('#ReasonRequest').html('<img src="images/ajax-loader.gif" />&nbsp; Saving Reason');
        
        DataReturnControl.AddRejectionMessageToRequest(sReason, sContactRequestOID, function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                $('#ReasonRequest').css({'font-weight':'normal','color':'green'});
                $('#ReasonRequest').html(res[1]);
            }else {
                $('#ReasonRequest').html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
   }
   
   function RequestPermissionToSeePDetails(sTalentOID)    {
        
        $('#PersonalDetailsRequestLink').html('Please enter a personal Message that will be delivered with this request (Optional)<br /><textarea id="PersonalMessageTA" onkeyup="checkWordLen(this, 100, 500);" onblur="checkWordLen(this, 100, 500);"></textarea><br /><span id="WordCountValue">0</span>/100 Words, <span id="CharacterCountValue">0</span>/500 Characters<br /><br />Then Click <a href="#" onclick="SendRequestPermissionToSeePDetails(' + sTalentOID + ');return false;">Here</a>.');
   }
            
   function SendRequestPermissionToSeePDetails(sTalentOID)    {
        var sPersonalMessage = $('#PersonalMessageTA').val();
        
        $('#PersonalDetailsRequestLink').html('<img src="images/ajax-loader.gif" />&nbsp; Checking Permissions');
        
        MyApplicationControl.RequestPermissionToViewPDetails(sTalentOID, sPersonalMessage, function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                $('#PersonalDetailsRequestLink').html(res[1]);
            }else {
                $('#PersonalDetailsRequestLink').html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
   }
   
   function SendContactRequest(sTalentOID, sContactMessage)    {
        var sEmail      = $('#ContactEmail').val(),
            bDontAskAgain   = $('#AskMeAgain').is(':checked');
        
        $('#PersonalDetailsRequestLink').html('<img src="images/ajax-loader.gif" />&nbsp; Sending Request');
        
        MyApplicationControl.SendContactRequest(sTalentOID, sEmail ,sContactMessage, bDontAskAgain, function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                $('#PersonalDetailsRequestLink').css({'font-weight':'normal','color':'green'});
                $('#PersonalDetailsRequestLink').html(res[1]);
            }else {
                $('#PersonalDetailsRequestLink').html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
   }
   
   function checkWordLen(obj, wordLen, iCharLength){
        var sWords = obj.value.split(/[\s]+/),
            len = obj.value.split(/[\s]+/).length,
            sCutValue = "";
            $('#WordCountValue').html(len).css({"color":"black","font-weight":"normal"});
            $('#CharacterCountValue').html(obj.value.length).css({"color":"black","font-weight":"normal"});
            
        if(wordLen !== 0 && wordLen !== "0")  {
            if(len > wordLen){
                for (i=0; i < wordLen; i++) {
                    sCutValue = sCutValue + sWords[i] + " ";
                }
                obj.value = sCutValue.substring(0, sCutValue.length-1);
                $('#WordCountValue').css({"color":"red","font-weight":"bold"});
                alert("You cannot use more than " + wordLen + " words.");
                obj.focus();
                return false;
            }
        }
        
        if(iCharLength !== 0 && iCharLength !== "0")  {
            if(obj.value.length > iCharLength)  {
                obj.value = obj.value.substring(0,iCharLength-1);
                $('#CharacterCountValue').css({"color":"red","font-weight":"bold"});
                alert("You cannot use more than " + iCharLength + " Characters.");
                obj.focus();
                return false;
            }
        }
        
        return true;
    }
    
    function AddRemoveTalentToBasket(sTalentOID, clickedElement)    {
        $(clickedElement).html('<img src="images/ajax-loader.gif" />');
    
        TalentSearchControl.AddRemoveTalentFromBasket(sTalentOID, function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                $(clickedElement).html(res[1]);
                $(clickedElement).css({'font-weight':'bold'});
                $('.AfterMessage').css({'font-weight':'bold','color':'green'})
                .animate({opacity:1.0}, 2000).fadeOut(1000);
                //setTimeout("$('.AfterMessage').fadeOut(1000);", 2000);
            }else {
                $(clickedElement).html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
    }
    
    function AddRemoveTalentToBasketMyApp(sTalentOID, clickedElement)    {
        $(clickedElement).html('<img src="images/ajax-loader.gif" />');
    
        MyApplicationControl.AddRemoveTalentFromBasket(sTalentOID, function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                $(clickedElement).html(res[1]);
                $('.AfterMessage').css({'font-weight':'bold','color':'green'})
                .animate({opacity:1.0}, 2000).fadeOut(1000);
            }else {
                $(clickedElement).html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
    }
    
    function AddRemoveTalentToBasketEmpJC(sTalentOID, clickedElement)    {
        $(clickedElement).html('<img src="images/ajax-loader.gif" />');
    
        EmpJobCentreControl.AddRemoveTalentFromBasket(sTalentOID, function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                $(clickedElement).html(res[1]);
                $('.AfterMessage').css({'font-weight':'bold','color':'green'})
                .animate({opacity:1.0}, 2000).fadeOut(1000);
            }else {
                $(clickedElement).html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
    }
    
    function AddContactReqAcceptExtraInfo(sContactRequestOID)    {
        var sReason = $('#AcceptExtraInfo').val();
        
        $('#AcceptFurtherInfo').html('<img src="images/ajax-loader.gif" />&nbsp; Saving Reason');
        
        DataReturnControl.AddAcceptMessageToRequest(sReason, sContactRequestOID, function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                $('#AcceptFurtherInfo').css({'font-weight':'normal','color':'green'});
                $('#AcceptFurtherInfo').html(res[1]);
            }else {
                $('#AcceptFurtherInfo').html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
   }
   
    function SendChampionEditRequestReply(sChampEditRightsRequestOID, bApprove)    {
        var sReason = $('#AcceptExtraInfo').val();
        
        $('#AcceptFurtherInfo').html('<img src="images/ajax-loader.gif" />&nbsp; Saving Reason');
        
        DataReturnControl.SendChampionEditRequestReply(sChampEditRightsRequestOID, bApprove, sReason, function(sReturn)   {
            var sResult = sReturn.value;
            $('#AcceptFurtherInfo').html(sResult);
        });
   }
   
   function ClearTalentHistory()    {
        var ClearHistoryHTML = $('#clearHistory').html();
        
        $('#clearHistory').html('<img src="images/ajax-loader.gif" />&nbsp; Clearing ...');
   
        EmpJobCentreControl.RemoveTalentHistory(function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                var iCount = 0;
                $('#RemovedTalent dt').each( function() {
                    $(this).animate({opacity:1.0}, iCount).fadeOut('slow');
                    setTimeout(function() {
                        var iRemovedCount = parseInt($('#RemovedTalent_Count').html(), 10) - 1;
                        $('#RemovedTalent_Count').html(iRemovedCount.toString());
                    },iCount);
                    iCount += 1000;
                });
                $('#clearHistory').css({'font-weight':'normal','color':'green'});
                $('#clearHistory').html(res[1]).animate({opacity:1.0}, iCount, function()   {
                    $('#clearHistory').fadeOut('slow', function()   {
                        $('#clearHistory').html(ClearHistoryHTML).css('color','black').fadeIn('slow');
                        $('#RemovedTalent dl').css({'display':'none','color':'black'}).html('None').fadeIn('slow');
                    });
                });
            }else {
                $('#clearHistory').html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
   }
      function ClearTalentProfileHistory()    {
        var ClearHistoryHTML = $('#clearHistory').html();
      
        $('#clearHistory').html('<img src="images/ajax-loader.gif" />&nbsp; Clearing ...');
   
        MyJobCentreControl.RemoveTalentProfileHistory(function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                var iCount = 0;
                $('#DeletedTalent dt').each( function() {
                    $(this).animate({opacity:1.0}, iCount).fadeOut('slow');
                    setTimeout(function() {
                        var iDeletedCount = parseInt($('#DeletedTalent_Count').html(), 10) - 1;
                        $('#DeletedTalent_Count').html(iDeletedCount.toString());
                    },iCount);
                    iCount += 1000;
                });
                $('#clearHistory').css({'font-weight':'normal','color':'green'});
                $('#clearHistory').html(res[1]).animate({opacity:1.0}, iCount, function()   {
                    $('#clearHistory').fadeOut('slow', function()   {
                        $('#clearHistory').html(ClearHistoryHTML).css('color','black').fadeIn('slow');
                        $('#DeletedTalent dl').css({'display':'none','color':'black'}).html('None').fadeIn('slow');
                    });
                });
            }else {
                $('#clearHistory').html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
   }
   
   function DeleteOrReInstateTalentProfile(sTalentOID, clickedElement)    {
        $(clickedElement).html('<img src="images/ajax-loader.gif" />');
    
        MyJobCentreControl.DeleteOrReinstateTalentProfile(sTalentOID, function(sReturn)   {
            var sResult = sReturn.value;
            var res = sResult.split('|');
            if (res[0] == 1)  {
                $(clickedElement).html(res[2]).animate({opacity:1.0}, 2000, function()  {
                    $(clickedElement).parents('dt').fadeTo('slow', 0, function() {
                        var eList = $(clickedElement).parents('dl')[0],
                            eDepartureCount = $(clickedElement).parents('.todo').children('h5').children('a').children('span')[0],
                            iDepartureCount = parseInt($(eDepartureCount).html(), 10) - 1;
                            
                        $(eDepartureCount).html(iDepartureCount.toString());
                        $(clickedElement).parents('dt').remove();
                        if($("dt", eList).length === 0)   {
                            $(eList).hide().html("None").fadeIn('slow');
                        }
                        if($('#' + res[3] + ' dt').length === 0)  {
                            $('#' + res[3] + ' dl').html("");
                        }
                        $('#' + res[3] + ' dl').append(res[1]);
                        var iDestinationCount = parseInt($('#' + res[3] + '_Count').html(), 10) + 1;
                        $('#' + res[3] + '_Count').html(iDestinationCount.toString());
                        $('#Talent' + sTalentOID).css('opacity','0').fadeTo('slow', 1.0);
                    });
                });
            }else {
                $(clickedElement).html(res[1]).
				css({"color":"red","font-weight":"bold"});
			}
        });
    }
    
    function ShowDeactivateButttons(eClicked)    {
        var eDT = $(eClicked).parents('dt')[0];
        $('.TalentDetails' ,eDT).css('display','none');
        $('.DeActivateDropDown' ,eDT).fadeIn('slow');
    }
    
    function DeActivateTalent(sTalentOID, eClicked) {
        var eDT = $(eClicked).parents('dt')[0],
            sReason = "";
        
        switch ($('.ReasonDD', eDT).val()) {
            case "0":
                sReason = $('.ReasonDD :selected', eDT).text();
                break;
            case "1":
                $('.DeActivateDropDown', eDT).css('display','none');
                $('.DeActivateReasonOther', eDT).fadeIn('slow');
                if($('.DeActivateReasonOther input', eDT).val() === "") {
                    return false;
                } else  {
                    sReason = $('.DeActivateReasonOther input', eDT).val();
                }
                break;
        }
        
        if (confirm($('#ConfirmText').val()))    {
            MyJobCentreControl.DeActivateTalent(sTalentOID, sReason, function(sReturn){
               var sResult = sReturn.value,
                   res = sResult.split('|');
                if (res[0] == 1)  {
                    $(eDT).fadeTo('slow', 0, function() {
                        var eList = $(eDT).parents('dl')[0],
                            eDepartureCount = $(eDT).parents('.todo').children('h5').children('a').children('span')[0],
                            iDepartureCount = parseInt($(eDepartureCount).html(), 10) - 1;
                            
                        $(eDepartureCount).html(iDepartureCount.toString());
                        $(eDT).remove();
                        if($("dt", eList).length === 0)   {
                            $(eList).hide().html("None").fadeIn('slow');
                        }
                        if($('#DeletedTalent dt').length === 0)  {
                            $('#DeletedTalent dl').html("");
                        }
                        var iDestinationCount = parseInt($('#DeletedTalent_Count').html(), 10) + 1;
                        $('#DeletedTalent_Count').html(iDestinationCount.toString());
                        $('#DeletedTalent dl').append(res[1]);
                        $('#Talent' + sTalentOID).css('opacity','0').fadeTo('slow', 1.0);
                    });
                }else {
                    $(eDT).html(res[1]).
				    css({"color":"red","font-weight":"bold"});
			    }     
            });
        }   else    {
            $('.DeActivateReasonOther input', eDT).val('');
            $('.ReasonDD', eDT).get(0).selectedIndex = 0;
            $('.DeActivationText', eDT).fadeOut('slow', function()  {
                $('.TalentDetails', eDT).fadeIn('slow');
            });
        }
    }
    
    function RetractContactRequest(sTalentOID)  {
        $('#RetractContactRequest').fadeOut('slow', function()   {
            $('#RetractionReason').fadeIn('slow', function()    {
                $('#PersonalMessageTA').attr('disabled',false);
            });
            
        });
    }
    
    function SubmitContactRequest(sTalentOID)   {
        var sReason = $('#PersonalMessageTA').val();
        $('#RetractionReason').html('<img src="images/ajax-loader.gif" />&nbsp; Retracting ...');
        
        if (confirm($('#RetractionConfirmText').val()))  {
            MyApplicationControl.RetractContactRequest(sTalentOID, sReason, function(sReturn){
               var sResult = sReturn.value,
                   res = sResult.split('|');
                if (res[0] == 1)  {
                    $('#RetractionReason').html(res[1]);
                }else {
                    $('#RetractionReason').html(res[1]).
			        css({"color":"red","font-weight":"bold"});
		        }
            });
        }   else    {
            $('#RetractionReason').fadeOut('slow', function()   {
                $('#RetractContactRequestRetractionReason').fadeIn('slow');
			});
        }
    }
    
    function CancelDeActivation(eClicked)	{
		var eParentDT = $(eClicked).parents('dt').get(0);
		
		$('.DeActivateReasonOther input', eParentDT).val('');
        $('.ReasonDD', eParentDT).get(0).selectedIndex = 0;
		$('.DeActivationText', eParentDT).css('display','none');
		$('.TalentDetails', eParentDT).fadeIn('slow');
	}
	
	function RemoveSuggestedJobFromList(sTalentOID, eClicked)   {
	    var eParentDiv = $(eClicked).parents('div').get(0),
	        sJobTitle = $('span.JobTitle' ,eParentDiv).text(),
	        sJobOID =  $(eParentDiv).attr('OID');
	    
	    $(eClicked).html('<img src="images/ajax-loader.gif" />&nbsp;Removing');
	    
	    GetSpottedControl.RemoveJobFromSuggestedList(sTalentOID, sJobOID, sJobTitle, function(sReturn){
           var sResult = sReturn.value,
               res = sResult.split('|');
            if (res[0] == 1)  {
	            $(eClicked).html(res[1]).css('color','green').animate({opacity:1.0}, 2000, function()  {
	                $(eParentDiv).fadeOut('slow', function() {
	                    $(eParentDiv).remove();
	                });
	            });
            }else {
                $(eClicked).html(res[1]).
		        css({"color":"red","font-weight":"bold"});
	        }
	        
            $('#JobTitlesAddButton').fadeIn('slow');
	    });
	}
	
		var _JobTitleSearchSuggestions = '';
    
    function JobTitleSearchSuggestions() {
        if (_JobTitleSearchSuggestions === '') {
        var pathwayIDs = [];
        $(".PathwayCheckBox:checked").each(function (i) 
        {
            pathwayIDs.push(this.id.substr(4));                
        });
            _JobTitleSearchSuggestions = getDataForJobTitlesForSearchSuggestBox(pathwayIDs);
        }
        return getValArray(_JobTitleSearchSuggestions);
    }
    
    function getDataForJobTitlesForSearchSuggestBox(pathwayIDs)  {
	    var sResult = TalentSearchControl.GetSuggestionOptions(pathwayIDs).value
        res = sResult.split('|');
        if (res[0] == 0)  {
            alert(res[1]);
            return false;
        }   else    {
            return JSON.parse(sResult);
        }
    }
    
    function SelectSearchSuggestedJob(value)   {
        AddJobToListOfSearchJobs(getVal(_JobTitleSearchSuggestions, value), value);
    }
	
	function GetSuggestedJobAddListForSearch()  {
	    $('#JobTitlesAddButton').css('display','none');
	    $('#SuggestedJobMessages').html('<img src="images/ajax-loader.gif" />&nbsp;Loading').fadeIn(0, function()   {
	        $('#autoCompleteSuggestedJobs').setOptions({data:JobTitleSearchSuggestions(), onItemSelect:SelectSearchSuggestedJob ,matchContains:true, minChars: 1});
    	    $('#SuggestedJobMessages').fadeOut(0)
	        $('#AddSuggestedJobDD').fadeIn('fast', function()   {
    	        $('#autoCompleteSuggestedJobs').get(0).focus();
	        });
	    });
	}
	
	function AddJobToListOfSearchJobs(sJobOID, sJobTitle)  {
	    var sHTML = '<div OID="' + sJobOID + '" class="SuggestedJobItem"><a href="#" onclick="RemoveSuggestedJobFromSearchList(this);return false;" class="RemoveSuggestedJobLink">(Remove)<img src="images/uksp/delete.png" /></a><span class="JobTitle">' + sJobTitle + '</span></div>',
	        bExisting = false;
	        $('#AddSuggestedJobDD').css('display','none');
	        
            $("#JobTitles div.SuggestedJobItem").each(function () 
            {
                if (sJobOID == "0") {
                    if (sJobTitle == $('span.JobTitle' ,this).text())   {
	                    bExisting = true;
	                    $('#SuggestedJobMessages').fadeIn(0).html('This Job has already been added');
	                    css({"color":"red","font-weight":"bold"}).animate({opacity:1.0}, 1000, function()  {
                            $('#SuggestedJobMessages').fadeOut('fast', function()  {
                                $('#SuggestedJobMessages').css({"color":"black","font-weight":"normal"});
                                $('#JobTitlesAddButton').fadeIn('slow');
	                        });
	                    });;
                    }
                }   else    {
                    if (sJobOID == $(this).attr('OID')) {
	                    bExisting = true;
	                    $('#SuggestedJobMessages').fadeIn(0).html('This Job has already been added');
		                css({"color":"red","font-weight":"bold"}).animate({opacity:1.0}, 1000, function()  {
	                        $('#SuggestedJobMessages').fadeOut('fast', function()  {
	                            $('#SuggestedJobMessages').css({"color":"black","font-weight":"normal"});
                                $('#JobTitlesAddButton').fadeIn('slow');
	                        });
	                    });;
                    }
                }
                
            });
	    if (!bExisting) {
	        $('#AddSuggestedJobDD').css('display','none');
	        $('#SuggestedJobMessages').fadeIn(0).html('<img src="images/ajax-loader.gif" />&nbsp;Adding Job');
    	    
    	    
            $('#SuggestedJobMessages').html('Added').css('color','green').animate({opacity:1.0}, 1000, function()  {
                $('#SuggestedJobMessages').fadeOut('fast', function()  {
                    $('#SuggestedJobMessages').html('Added').css('color','black');
                    if ($('#JobTitles div').length != 5) {
                        $('#JobTitlesAddButton').fadeIn('slow');
                    }
                });
            });
            $('#JobTitles').append(sHTML);
            $('#JobTitles div :last').css('display','none');
            $('#JobTitles div :last').fadeIn('slow');
        }
        _JobTitleSearchSuggestions = '';
        $('#autoCompleteSuggestedJobs').flushCache();
        $('#autoCompleteSuggestedJobs').val('');
	}
	
	function RemoveSuggestedJobFromSearchList(eClicked)   {
	    var eParentDiv = $(eClicked).parents('div').get(0);
	    
	    $(eClicked).html('<img src="images/ajax-loader.gif" />&nbsp;Removing');
        $(eClicked).html('Removed').css('color','green').animate({opacity:1.0}, 2000, function()  {
            $(eParentDiv).fadeOut('slow', function() {
                $(eParentDiv).remove();
            });
        });
        
        $('#JobTitlesAddButton').fadeIn('slow');
	}
	
	function getDataForTalentProfileSuggestBox(sTalentOID)  {
	    var sResult = GetSpottedControl.GetSuggestionOptions(sTalentOID).value
        res = sResult.split('|');
        if (res[0] == 0)  {
            alert(res[1]);
            return false;
        }   else    {
            return JSON.parse(sResult);
        }
    }

    function getVal(myDict, myVal)  {
	    if (myDict.hasOwnProperty(myVal))   {
		    return(myDict[myVal]);
	    }   else    {
		    return('-1');
	    }
    }

    function getValArray(e) {
	    var res = [];
	    var i = 0;
        for (c in e)    {
		    if  (e.hasOwnProperty(c))   {
			    res[i] = c;
			    i++;
		    }
        }
	    return res;
    }

    var _TalentIndividualSuggestions = '';
    
    function TalentIndividualSuggestions() {
        if (_TalentIndividualSuggestions === '') {
            var sTalentOID = $('#TalentOID').val();
            _TalentIndividualSuggestions = getDataForTalentProfileSuggestBox(sTalentOID);
        }
        return getValArray(_TalentIndividualSuggestions);
    }
    
    function SelectIndividualSuggestedJob(value)   {
        AddJobToListOfSuggestedJobsFromAutoSelect(getVal(_TalentIndividualSuggestions, value), value, $('#TalentOID').val());
    }

    function AddJobToListOfSuggestedJobsFromAutoSelect(sJobOID, sJobTitle, sTalentOID)  {
	    $('#AddSuggestedJobDD').css('display','none');
	    $('#SuggestedJobMessages').fadeIn(0).html('<img src="images/ajax-loader.gif" />&nbsp;Adding Job');
	    
	    GetSpottedControl.AddJobToSuggestedList(sTalentOID, sJobOID, sJobTitle, function(sReturn){
           var sResult = sReturn.value,
               res = sResult.split('|');
            if (res[0] == 1)  {
	            $('#SuggestedJobMessages').html('Added').css('color','green').animate({opacity:1.0}, 1000, function()  {
	                $('#SuggestedJobMessages').fadeOut('fast', function()  {
	                    $('#SuggestedJobMessages').html('Added').css('color','black');
	                    if ($('#JobTitles div').length != 5) {
                            $('#JobTitlesAddButton').fadeIn('slow');
                        }
	                });
	            });
                $('#JobTitles').append(res[1]);
                $('#JobTitles div :last').css('display','none');
                $('#JobTitles div :last').fadeIn('slow');
                _TalentIndividualSuggestions = '';
                $('#autoCompleteSuggestedJobs').flushCache();
	            $('#autoCompleteSuggestedJobs').val('');
            }else {
                $('#SuggestedJobMessages').html(res[1]).
		        css({"color":"red","font-weight":"bold"}).animate({opacity:1.0}, 1000, function()  {
	                $('#SuggestedJobMessages').fadeOut('fast', function()  {
	                    $('#SuggestedJobMessages').css({"color":"black","font-weight":"normal"});
	                    if ($('#JobTitles div').length != 5) {
                            $('#JobTitlesAddButton').fadeIn('slow');
                        }
                        _TalentIndividualSuggestions = '';
                        $('#autoCompleteSuggestedJobs').flushCache();
                        $('#autoCompleteSuggestedJobs').val('');
	                });
	            });
	        }
	    });
	}
	
	function GetSuggestedJobAddList(sTalentOID) {
	    $('#JobTitlesAddButton').css('display','none');
	    $('#SuggestedJobMessages').html('<img src="images/ajax-loader.gif" />&nbsp;Loading').fadeIn(0, function()   {
	        $('#autoCompleteSuggestedJobs').setOptions({data:TalentIndividualSuggestions(), onItemSelect:SelectIndividualSuggestedJob ,matchContains:true, minChars: 1});
    	    $('#SuggestedJobMessages').fadeOut(0)
	        $('#AddSuggestedJobDD').fadeIn('fast', function()   {
    	        $('#autoCompleteSuggestedJobs').get(0).focus();
	        });
	    });
	}
	
	function CancelAddingSuggestedJob() {
	    $('#AddSuggestedJobDD').fadeOut('slow', function() {
	        $('#JobTitlesAddButton').fadeIn('slow');
	        _TalentIndividualSuggestions = '';
	        _JobTitleSearchSuggestions = '';
	        $('#autoCompleteSuggestedJobs').flushCache();
	        $('#autoCompleteSuggestedJobs').val('');
	    });
	}
	
	function AddCustomSuggestedJobRole()  {
	    var sJobTitle = $('#autoCompleteSuggestedJobs').val();
	    $('#AddSuggestedJobDD').css('display','none');
	    $('#SuggestedJobMessages').fadeIn(0).html('<img src="images/ajax-loader.gif" />&nbsp;Adding Job');
        
	    
	    GetSpottedControl.AddJobToSuggestedList($('#TalentOID').val(), "0", sJobTitle, function(sReturn){
           var sResult = sReturn.value,
               res = sResult.split('|');
            if (res[0] == 1)  {
	            $('#SuggestedJobMessages').html('Added').css('color','green').animate({opacity:1.0}, 1000, function()  {
	                $('#SuggestedJobMessages').fadeOut('fast', function()  {
	                    $('#SuggestedJobMessages').html('Added').css('color','black');
	                    if ($('#JobTitles div').length != 5) {
                            $('#JobTitlesAddButton').fadeIn('slow');
                        }
	                });
	            });
                $('#JobTitles').append(res[1]);
                $('#JobTitles div :last').css('display','none');
                $('#JobTitles div :last').fadeIn('slow');
                _TalentIndividualSuggestions = '';
                $('#autoCompleteSuggestedJobs').flushCache();
	            $('#autoCompleteSuggestedJobs').val('');
            }else {
                $('#SuggestedJobMessages').html(res[1]).
		        css({"color":"red","font-weight":"bold"}).animate({opacity:1.0}, 1000, function()  {
	                $('#SuggestedJobMessages').fadeOut('fast', function()  {
	                    $('#SuggestedJobMessages').css({"color":"black","font-weight":"normal"});
	                    if ($('#JobTitles div').length != 5) {
                            $('#JobTitlesAddButton').fadeIn('slow');
                            _TalentIndividualSuggestions = '';
                            $('#autoCompleteSuggestedJobs').flushCache();
	                        $('#autoCompleteSuggestedJobs').val('');
                        }
	                });
	            });
	        }
	    });
	}
	
	function showAllIndividualJobSuggestions()  {
    	setTimeout(function() {
            $('#autoCompleteSuggestedJobs').get(0).focus();
	        $('#autoCompleteSuggestedJobs').val('%').trigger("focus").trigger("click").trigger("click");
        },150);
    	
	    return false;
	}
	
	function SearchEBlasts()    {
	    $('#eBlastsList').html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Loading eBlasts</span>');
	    
	    EBlastsControl.SearchEBlasts($('#SearchText').val(), function(sReturn){
           var sResult = sReturn.value;
	        $('#eBlastsList').html(sResult);
	        initPopUp();
	    });
	}
	
	function MoveEBlastPage(sNextOrPrevious)    {
	    $('#eBlastsList').html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Loading eBlasts</span>');
	    
	    EBlastsControl.ChangeEBlastsPage(sNextOrPrevious, function(sReturn){
           var sResult = sReturn.value;
	        $('#eBlastsList').html(sResult);
	        initPopUp();
	    });
	}
	
     function SendEBlastEmail(sOID) {
	    $('#EmailButtons').html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Sending eBlast</span>');
        
        EBlastPopupControl.SendEBlastEmail(sOID, function(sReturn){
           var sResult = sReturn.value;
	        $('#EmailButtons').html(sResult);
	    });
     }
	

	function AuditApplication(id)
	{
	    $("a[href^='mailto']").click(function () { 
	    
	         if ($('#jobSummaryBox').length > 0)
	         VacancyInfoControl.FireAuditApplication(id);
	            else
	           
             JobVacancyControl.FireAuditApplication(id);
            
            //do nothing yet           
            //alert('Notify People 1st that User ' + id  + ' Looked at ' + entity + ' id ' + id);  
        });

    }

    function AuditVacancyApplyLinkHit(id) {
        VacancyInfoControl.FireAuditApplication(id);
    }
	
	// the function that is called to replace all data holders on the page.
	function ReplaceDataHolders()   {
	    
	    HeaderControl.GetDataCounts(function(res)  {
	        var sResult = res.value,
	            dic = JSON.parse(sResult);
    	    
	        for(element in dic) {
	            if (dic.hasOwnProperty(element))    {
	                $('.' + element).html(dic[element]);
	            }
	        }
	    });
	}
	
	function ShowHideCategoryBenefits(sOID) {
	var sHTML2Show = $('#CatBens' + sOID).html();
	    $('#BenefitsList').html(sHTML2Show);
	}
	
	function GetNextBenifits(iHowMany)  {
	    if ($('.BenefitsLoader').length == 0)   {
	        $('#Benefits').html('');
	    }
	    if ($('#Benefits').html() === "")   {
	        $('#Benefits').html('<span class="loadingMessage BenefitsLoader"><img src="images/ajax-loader.gif" />&nbsp;Loading Benefits...</span>');
	    }
	    
	    BenefitCheckerControl.GetNextBenefits(iHowMany, function(res)    {
	        $('.BenefitsLoader').remove()
	        $('#Benefits').append(res.value);
	        var iCount = 0;
            $('.new').each( function() {
                $(this).animate({opacity:1.0}, iCount).fadeIn('slow');
                $(this).removeClass('new');
                iCount += 1000;
            });
	    });
	}
	
	function CheckAllBenefits() {
	    $('#Benefits').html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Checking Benefits this could take some time..</span>');
	    
	    BenefitCheckerControl.CheckAllBenefits(function(res)    {
	        $('#Benefits').html(res.value);
	    });
	}
	
	function UpdateBenefit(sOID, bNew)    {
	    var eBenefit,
	        eNewHTML;
	
	    if (!bNew)  {
	        if ($('#Benefit' + sOID).attr('class') === "Removed")   {
	            eBenefit = $('#Benefit' + sOID).html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Removing..</span>').get(0);
	        }   else    {
	            eBenefit = $('#Benefit' + sOID).html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Refreshing..</span>').get(0);
	        }
	    }   else    {
	        eBenefit = $('#OrigonalBenefit' + sOID).html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Adding..</span>').get(0);
	    }
	    
	    BenefitCheckerControl.RefreshAnBenefit(sOID, bNew, function(res)  {
	        eNewHTML = $(res.value);
	        $(eBenefit).replaceWith(eNewHTML);
	        $(eNewHTML).fadeIn();
	        if($(eNewHTML).attr('class') === "RemovedMessage") {
	            $(eNewHTML).animate({opacity:1.0}, 2000).fadeOut('slow');
	        }
	    });
	}
	
	function TriggerAllBenefitUpdates() {
	    if(confirm('This will update all outdated benefits - Should I proceed?')) {
	        $('.Changed a').each(function() {
	            $(this).click();
	        });
	    }
	}
	
	function TruggerAllBenefitRemoves() {
	    if(confirm('This will remove all missing benefits - Should I proceed?')) {
	    	$('.Removed a').each(function() {
	            $(this).click();
	        });
	    }
	}
	
	function TriggerAllBenefitAdds() {
	    if(confirm('This will Add all missing benefits - Should I proceed?')) {
	    	$('.NewBenefit a').each(function() {
	            $(this).click();
	        });
	    }
	}
	
	function HideAllOKBenefits()    {
	    $(".NoChange").hide();
	}
	
    function GetJSONForSection(elementToGet)    {
       var params = {};

       $(elementToGet + " input, " + elementToGet + " select, " + elementToGet + " textarea").each(function() {
            if (this.type === 'checkbox') {
                params[this.id] = this.checked;
            }
            else if (this.type === 'select') {
                params[this.id] = this.options[this.selectedIndex].value;
            }
            else {
               if (this.type !== 'button') {
               params[this.id] = this.value;
                }
            }
        });
       return JSON.stringify(params);
   }
   
   function CheckTPPreveiwReadyStatus() {
        var iProfileOID = $('#ProfileList').val();
        
        if (iProfileOID === "0")   {
            alert('Before you can preview your Listing you must attach a CV');
            return false;
        }
        return true;
   }
   
   function ShowBenFromSearch(res)  {
        SimpleModal.open('BenefitPopup.aspx?id=' + res.id, 535, 720);
        $('#BenefitsSearchBox').val("");
   }
   
   function LoadGreatPlaces2WorkVic(sName)  {
       $('#greatPlaces2WorkVids').html('<embed src="mediaplayer.swf" allowscriptaccess="always" allowfullscreen="true" width="470" height="300" flashvars="autostart=true&repeat=false&file=GreatPlaces2Work/' + sName + '.flv" />');
   }
   
   function VacSearchJumpToPage(strPage, maxpages, adjust)  {
        var id = parseInt(strPage, 10);
        if (adjust === -1 )	{
			id = id -1;
        }
        if (!isNaN(id) && id > -1 && id < maxpages)	{
                Place(VacancySearchControl.ChangePage(id-1));
		}	else	{
			alert('Page Not Found');
		}
   }				

    function ShowVacanciesRSS() {
        try {
            var sTitle = document.getElementById('SimplifiedSearch').value;	
            if ($('#SimplifiedSearch.watermarkOn').length > 0)  {
                sTitle = "";
            }
                        
            var sLocation = document.getElementById('SimplifiedSearchLoc').value;	
            if ($('#SimplifiedSearchLoc.watermarkOn').length > 0 )  {
                sLocation = "";
            }
            //path = 
            //$('base').attr('href') + path.replace(/^\//, '');
            window.open($('base').attr('href') + 'VacanciesRSS.aspx?keywords=' + sTitle + '&Location=' +  sLocation);
        }   catch (problm)  {
            window.open($('base').attr('href') +  'VacanciesRSS.aspx');
        }
   }
   
   function ShowRSSFeed(sURL, sDivID) {
        $("#" + sDivID).html('<span class="loadingMessage BenefitsLoader"><img src="images/ajax-loader.gif" />&nbsp;Loading RSS...</span>');
	    HeaderControl.GetRSSFeedFromURL(sURL, function (res)    {
	        $("#" + sDivID).html(res.value);
	    });
    }
    
    function ShowRSSFeedNoTitle(sURL, sDivID) {
        $("#" + sDivID).html('<span class="loadingMessage BenefitsLoader"><img src="images/ajax-loader.gif" />&nbsp;Loading RSS...</span>');
	    HeaderControl.GetRSSFeedFromURLNoTitle(sURL, function (res)    {
	        $("#" + sDivID).html(res.value);
	    });
    }
    
    
    function SaveAndUpdateEmployerRSS(sEmployerOID) {
        var sURL = $('#RSSUrl').val(),
            sSaveButton = $('#RSSSaveAndUpdate').html();
        
        $('#RSSSaveAndUpdate').html('<span class="loadingMessage BenefitsLoader"><img src="images/ajax-loader.gif" />&nbsp;Saving URL...</span>');
        
        GoodEmployerFeatureControl.EditRSSURL(sEmployerOID, sURL, function(res) {
            if (res.value)  {
                if ($('#GENewsFeed').length === 0)    {
                    $('#RSSEdit').after('<div id="GENewsFeed"></div>');
                }
                
                $('#RSSSaveAndUpdate').html(sSaveButton);
                
                if (sURL !== "")    {
                    ShowRSSFeed(sURL, 'GENewsFeed');
                }   else    {
                    $('#GENewsFeed').empty();
                }
            }   else    {
                $('#RSSSaveAndUpdate').html(sSaveButton);
                alert('Saving Failed .. please try refreshing the page, you may of been logged out.');
            }
        });
    }
    
    function FireCreateQualsPDF()   {
        QualSearchResultsControl.FireCreateQualsPDF();
    }
    
    function SlideInOutElement(sElementID, eClickedIcon)    {
        if ($('#' + sElementID).is(':visible'))    {
            $(eClickedIcon).attr('src', 'images/uksp/add.png');
            $('#' + sElementID).slideUp('slow');
        }   else    {
            $(eClickedIcon).attr('src', 'images/uksp/arrow_up.png');
            $('#' + sElementID).slideDown('slow');
        }
    }
    
    function UpdateQualFilters()    {
        var chkEngland = $('#chkEngland').is(':checked'),
            chkWales = $('#chkWales').is(':checked'),
            chkNI = $('#chkNI').is(':checked'),
            chkScotland = $('#chkScotland').is(':checked'),
            chkPreEmp = $('#chkPreEmp').is(':checked'),
            chkSafe = $('#chkSafe').is(':checked'),
            chkWorkforce = $('#chkWorkforce').is(':checked'),
            chkProg = $('#chkProg').is(':checked'),
            courseType = $('#courseType').val();
            
        location.href = QualSearchResultsControl.UpdateURL(location.href, chkEngland, chkWales, chkNI, chkScotland, chkPreEmp, chkSafe, chkWorkforce, chkProg, courseType).value;
    }
    
    function CheckForJobSettingInQualSearch(eClicked)   {
        if ($('#chkPreEmp').is(':checked') || $('#chkSafe').is(':checked') || $('#chkWorkforce').is(':checked') || $('#chkProg').is(':checked'))  {
            $('#displayBy').val('Job');
            $(eClicked).parents('table').after('<p id="QualJobNote">*please note as you have chosen to filter results by qualification level your results will be displayed by job role</p>');
        }
    }
    
    function ShowApplicationAsPDF(cntrl, id)    {
        SpinMe(cntrl, "Creating PDF...");
        MyRelevantQualDisplayControl.FireCreatePDF(id); 
        UnSpinMe(cntrl);
    }

function ShowHideSection(eClicked)  {
    var sClassName = $(eClicked).attr('class').split(' ')[0];
    
    if ($('span.' + sClassName).is(':visible')) {
		//alert('Sliding ' + sClassName + ' Span Up, and div down');
        $('span.' + sClassName).slideUp('slow', function()  {
            $('div.' + sClassName + ' p').slideDown('slow');
        });
        $('div.' + sClassName + ' h3').removeClass('Open');
    }   else    {
		//alert('Sliding ' + sClassName + ' div Up, and span down');
        $('div.' + sClassName + ' p').slideUp('slow', function()   {
            $('span.' + sClassName).slideDown('slow');
        });
        $('div.' + sClassName + ' h3').addClass('Open');
        $('div.' + sClassName + ' h3').addClass('Open');
    }
}

function CheckPostCodeOnRegestration(eClicked)  {

    //var pcexp = '^[a-zA-Z]{1,2}[0-9]{1,2}\\s?[0-9]{1}[a-zA-Z]{2}$';
    var pcexp = '^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$';

    var myRegEx = new RegExp(pcexp, ''),
        sPostCode = $(eClicked).val();
    
    $('#addresspicker').html('');
    $('.requestMessage').remove();
    $('.postCodeWarning').remove();
    $("#fAddress1").attr('disabled', 'disabled');
    $("#fAddress1").removeAttr('style');
    $("#fAddress2").attr('disabled', 'disabled');
    $("#fAddress2").removeAttr('style');
    $("#fTown").attr('disabled', 'disabled');
    $("#fTown").removeAttr('style');
    $("#fCounty").attr('disabled', 'disabled');
    $("#fCounty").removeAttr('style');
    $("#fCountry").attr('disabled', 'disabled');
    $("#fCountry").removeAttr('style');
    $("#fPostcode").removeAttr('style');
               
    if (sPostCode === '')  {
        $('.postCodeWarning').remove();
        $(eClicked).css('background-color', '#F8AF42');
        $(eClicked).after('<div class="postCodeWarning">A postcode is required</div>');
        setTimeout(function()   {$(eClicked)[0].focus();}, 100);
        /*setTimeout(function()   {
            $('.postCodeWarning').fadeOut(1000, function()  {
                $('.postCodeWarning').remove();
            });
        }, 2000);*/
        
    }   else if (!myRegEx.test(sPostCode) && sPostCode !== "")    {
        $('.postCodeWarning').remove();
        $(eClicked).css('background-color', '#F8AF42');
        $(eClicked).after('<div class="postCodeWarning">This postcode is invalid.</div>');
        setTimeout(function()   {$(eClicked)[0].focus();}, 100);
    }   else    {
        LookupPostcode($('#PostcodeSearch').get(0));
    }
}

function DisablePostCodeValidation()    {
    $('#fPostcode').removeAttr('onBlur');
    $('#PostcodeSearch').css('display','none');
    $('#fAddress1').removeAttr('disabled');
    $('#fAddress2').removeAttr('disabled');
    $('#fTown').removeAttr('disabled');
    $('#fCounty').removeAttr('disabled');
    $('#fCountry').removeAttr('disabled');
    $('#NoUKPostCodeSpan').html('Please Enter your details Manually');
    $('#NoUKPostCodeSpan').attr('class','true');
}

function AddRefinementCloses()  {
    $('li.refinement span').each(function()  {
        $(this).click(function(){
            $(this).parent().fadeOut('slow', function() {
                $(this).remove();
            });
        });
    });
}

function AttachNewFileToEmail(sPath, sName)    {
    SendApplicationEmailControl.GetHTMLForFile(sPath, sName, function(res) {
        $('#AttachedFiles').append(res.value);
        AddRefinementCloses();
    });
}

function SendApplicationEmail(sVacID) {
    var sSubject = $('#EmailSubject').val(),
        sBody = $('#EmailBody').val(),
        arFiles = {},
        sOldHTML = $('#SendLink').html(),
        bIncludeMeOnEmail = $('#bIncludeMeOnEmail').is(':checked');
        
    if (sBody.indexOf('*****Your Text*****') != -1) {
        alert('Please replace the holder "*****Your Text*****" with a personal message before sending.');
        return false;
    }
    
    if (sBody.indexOf('<Name Here>') != -1 || sSubject.indexOf('<Name Here>') != -1) {
        alert('Please replace the holder "<Name Here>" with your name before sending.');
        return false;
    }
    
    if (sBody.indexOf('<Email Here>') != -1 || sSubject.indexOf('<Email Here>') != -1) {
        alert('Please replace the holder "<Email Here>" with your email address before sending.');
        return false;
    }
    
    if (sBody.indexOf('<Telephone Number Here>') != -1 || sSubject.indexOf('<Telephone Number Here>') != -1) {
        alert('Please replace the holder "<Telephone Number Here>" with your Telephone Number before sending.');
        return false;
    }
    
    if (sBody.indexOf('<Address Here>') != -1 || sSubject.indexOf('<Address Here>') != -1) {
        alert('Please replace the holder "<Address Here>" with your Correspondence Address before sending.');
        return false;
    }
            
    if ($('li.attachedFile').length == 0)
    {
        alert('Please attach your CV before sending');
        return false;
    }
            
    $('#SendLink').html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Sending Message...</span>');
    
    $('li.attachedFile').each(function()    {
        arFiles[$(this).children('p').html()] = $(this).attr('id');
    });
    
    SendApplicationEmailControl.SendEmail(sVacID, sSubject, sBody, JSON.stringify(arFiles), bIncludeMeOnEmail, function(res)   {
        var Results = res.value.split('|');
        
        if (Results[0] === "1")   {
            alert(Results[1]);
            SimpleModal.close();
        }   else    {
            alert(Results[1]);
            $('#SendLink').html(sOldHTML);
        }
    });
}

function reloadThis()
{  
    document.location.reload(); 
}

function ShowUKSPCVs()  {
    $('#AddUKSPCVQuestion').fadeOut(0);
    $('#UploadAnyFile').fadeOut(0);
    $('#UKSPCVs').fadeIn('slow');
}

function HideUKSPCVs()  {
    $('#UKSPCVs').fadeOut(0);
    $('#AddUKSPCVQuestion').fadeIn('slow');
    $('#UploadAnyFile').fadeIn('slow');
}

function VeiwAppPDF()   {
    SendApplicationEmailControl.FireCreatePDF($('#Apps').val());
}

function AttachUKSPCV()    {
    SendApplicationEmailControl.AttachUKSPPDF($('#Apps').val(), function(res) {
        $('#AttachedFiles').append(res.value);
        AddRefinementCloses();
        HideUKSPCVs();
    });
}

function ChangeCareerMapPopupTab(sTabNo)    {
    $('div.CareerMapPopup #LeftNav div').each(function()   {
        if ($(this).attr('id') !== 'Tab' + sTabNo)  {
            $(this).removeClass('Selected');
        }   else    {
            $(this).addClass('Selected');
        }
    });
    
    $('div.CareerMapPopup .RightPanel').each(function()   {
        if ($(this).attr('id') !== 'Panel' + sTabNo)  {
            $(this).css('display', 'none'); 
        }   else    {
            $(this).css('display', 'block');
        }
    });
}

function JumpToMarketplacePage(strPage, maxpages, adjust)  {
    var id = parseInt(strPage);
    if (adjust === -1 ) {
        id = id -1;
    }
    
    if (!isNaN(id) && id > -1 && id < maxpages) {
            VSWelcome_callback(WelcomeVSControl.ChangePage(id-1));
    }
    else    {
        alert('Page Not Found');
    }
}
   
function CheckSkillsPledgeQuestions(eClicked, sEmployerOID)    {
    var sQNumber = $(eClicked).attr('id').substring(13),
        bIsChecked = $(eClicked).is(':checked');
        
    $(eClicked).hide();
    $(eClicked).after('<span class="SkillsPledgeSavingMsg" id="QuestionSavingMsg' + sQNumber + '"><img src="images/ajax-loader.gif" /></span>');
    
    GoodEmployerEditControl.SaveSkillsPledgeQuestion(sQNumber, bIsChecked, sEmployerOID, function(res)   {
        if(res.value === "0")   {
            $('#QuestionSavingMsg' + sQNumber).css({'color':'red','font-weight':'bold'});
            $('#QuestionSavingMsg' + sQNumber).html('Saving Failed... please Refresh the Page and try again.');
            $('#bonusQ').hide();
        }
        else if (res.value ==="2")  {
            $('#QuestionSavingMsg' + sQNumber).remove();
            $(eClicked).show();
            $('#bonusQ').show();
            SimpleModal.open('EmployerPledgePopUp.aspx',480, 800, function(){});
        }
        else {
            $('#QuestionSavingMsg' + sQNumber).remove();
            $(eClicked).show();
            $('#bonusQ').hide();
        }
    });
}

function SetSkillsPledgeStatus(bResponse)   {
    $('#SPResponseButtons').html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Saving...</span>');
    EmployerPledgePopUpControl.SetSkillsPledgeStatus(bResponse, function(res)   {
        var sReturn = res.value,
            sParts = sReturn.split('|');
        
            alert(sParts[1]);
            SimpleModal.close();
    });
}

function SkillsPledgeStartupScript()    {
    var bNotSaidYesToAll = undefined,
        bAccepted = EmployerPledgePopUpControl.CheckEmployersSPStatus().value;
    $('#SPAlreadyAnsweredMsg').remove();
    if (bAccepted)  {
        $('#SkillsPledgeQuestions label,#SkillsPledgeQuestions div,#SkillsPledgeQuestions h3').fadeTo('slow', 0.5);
        $('#SkillsPledgeQuestions input').attr('disabled', true);
        $('#SkillsPledgeQuestions').after('<p id="SPAlreadyAnsweredMsg">You have already committied to the skills pledge.</p>');
    }
    else    {
        $('#SkillsPledgeQuestions input').each(function()    {
            if(!$(this).is(':checked')) {
                bNotSaidYesToAll = true;
            }
        });
        if (!bNotSaidYesToAll)  {
            $('#SkillsPledgeQuestions').after('<p id="SPAlreadyAnsweredMsg" style="color:black;">Last time you declined the skills pledge. <a href="#" onclick="SimpleModal.open(\'EmployerPledgePopUp.aspx\',550, 800, function(){});return false;">Click Here</a> to be asked again.</p>');
        }
    }
}


function SwapTab(paneID,cntrl)
{

    $(".simplepanes div").hide();
    $(".simpletabs li").css("background-color","#fff");
    $("#fund" + paneID ).show();
    $("#what" + paneID ).show();
    $("#post" + paneID ).show();
    $("#prov" + paneID ).show();
    
    setCookie('FavouriteNation',paneID, 365);
    
    $(cntrl).parents("li").css("background-color","#ccc");
    return false;
}

function FixAnchors() {
    $("a[href^='\#']").click(function(e) {
        e.preventDefault();
        document.location.hash = this.href.substr(this.href.indexOf('#') + 1);
    })
    if ($("mnuAccountMan").prev().length > 0)
        $("mnuAccountMan").prev()[0].onclick = "ToggleMenu('mnuAccountMan');return false;";
    
    
}

function GotoHash(hashAnchor) {
    document.location.hash = hashAnchor;
}

function AuditAdvertClick(bannerID) {
    HeaderControl.FireAuditAdvertClick(bannerID);
}




function HandleProtectedParagraphs() {
    try {
        if (HeaderControl.IsLoggedIn().value) {
            $(".Protected").show();
            $(".UnProtected").hide();
        }
        else {
            $(".UnProtected").show();
            $(".Protected").hide();
        }
        $("a[href^='login.aspx?ReturnUrl']").attr("href", "login.aspx?ReturnUrl=" + location.pathname );
        
        
    }
    catch (excp) {
        $(".UnProtected").show();
        $(".Protected").hide();
    }
}


function FilterQBy(className, thisElem) {
    $("#nationFilter a").removeClass("selct").addClass("notsel");
    $(thisElem).removeClass("notsel").addClass("selct");
    $(".flgE, .flgW, .flgN, .flgS").hide();
    $(className).show();
}

function RefreshRegionalJobs(sWhichRegion, elem) {
    var sTemplate = $('#template').val();
    var numPerRegion = $('#numperreg').val();

    var excludeEmpIDs = new Array();
    var alwaysIncludeVacancy = $("#vacid").val();
    $(".emp:checked").each(function(i) {
    excludeEmpIDs.push(this.id.substr(3));
    });


    if (sWhichRegion == 'All') {
        SpinMe($('#btn')[0], "Rebuilding list...");
        AdminJobsHelperControl.Rebuild(sTemplate, numPerRegion, sWhichRegion, excludeEmpIDs,alwaysIncludeVacancy, function(res) {
            Place(res);

            $("#jobslist h2").click(function(e)
            { RebuildRegionSection(e); }
        );
            UnSpinMe($('#btn')[0]);
        });
    }
    else {
        
        SpinMe($(elem.srcElement), "Rebuilding list...");
        AdminJobsHelperControl.Rebuild(sTemplate, numPerRegion, sWhichRegion, excludeEmpIDs, alwaysIncludeVacancy, function (res) {
            var section = $(elem.srcElement).text();
            var tableToReplace = $(elem.srcElement).next();
            parts = res.value.split('|');
            tableToReplace.replaceWith(parts[1]);
            $(elem.srcElement).next().remove();
            $(elem.srcElement).removeAttr("style"); 
            UnSpinMe($(elem.srcElement));
           
        });
    }


}

function FindSpecificVacancies() {

    var alwaysIncludeVacancy = $("#vacid").val();

    Place(AdminJobsHelperControl.FireFindSpecificVacancies(alwaysIncludeVacancy));
    
} 



function RebuildRegionSection(elem) {
    var section = $(elem.srcElement).text();
    RefreshRegionalJobs(section, elem);
    //$(elem.srcElement).next().remove();
}


function CopyToClipboard(divId) {
    if (navigator.userAgent.indexOf("Firefox")!=-1){
      alert('Firefox version of this is not working at the moment.  Please use IE.');
    }
    var txt = $(divId).html();
    txt = AdminJobsHelperControl.TransformToMailChimp(txt).value;



    $.copy(txt);




    $("#footer").before("<textarea rows='100' cols='100' id='tx'></textarea>");
    $("#tx").val(txt);
    
    alert('Copied to Clipboard');
}


function AskYPGQuestion(qText) {


    if (confirm(qText))
    {
        MyRelevantQualDisplayControl.FireSetYPG(true);
    }
    else
    {
        MyRelevantQualDisplayControl.FireSetYPG(false);
    }


    //$.prompt(qText, { buttons: { Yes: true, No: false },
    //callback: AskYPGQuestionCallback, opacity: 1, top: 60 
    
    // });
    
}


//function AskYPGQuestionCallback(v, m, f) {
//    if (v) {
//        alert('Oh yes');
        
    //}
//}


function DoSiteSearch() {
    var srchText = $("#srchText").val();
    location.href = "search.aspx?searchTerm=" + srchText;
    //SiteSearchControl.FirePageSearch(srchText,SearchCallback);

}


function SearchCallback(res) {
	var result = res.value,
	listTokens = result.split('|');

	if (listTokens[0] === '0') {
		alert(listTokens[1]);
	} else {
	document.getElementById(listTokens[0]).innerHTML = result.replace(listTokens[0] + '|','');
	}

	
}



function AsynchDataSearch() {
    var srchText = $("#srchText").val();
    SiteSearchControl.FireDataSearch("employers", srchText, SearchCallback);
    SiteSearchControl.FireDataSearch("providers", srchText, SearchCallback);
    SiteSearchControl.FireDataSearch("champions", srchText, SearchCallback);
    SiteSearchControl.FireDataSearch("quals", srchText, SearchCallback);
    SiteSearchControl.FireDataSearch("vacancies", srchText, SearchCallback);
    SiteSearchControl.FireDataSearch("jobdetails", srchText, SearchCallback);

}


function FurtherSearch(srchType) {
    var srchText = $("#srchText").val();
    if (srchType == 'employers') {
        location.href = "employers/" + srchText;
    }
    else if (srchType == 'vacancies') {
        location.href = "jobs/" + srchText;
    }
    else if (srchType == 'champions') {
        location.href = "OrganisationSearch.aspx";
    }
    else if (srchType == 'quals') {
        location.href = "qualsearch.aspx";
    }
    else if (srchType == 'providers') {
        location.href = "goodproviderguide.aspx";
    }
    else if (srchType == 'jobdetails') {
        location.href = "JobSearchResults.aspx?searchTerm=" + srchText;
    }
    else {
        alert('To do');
    }

}


function ActivateSiteSearch()
{
    $("#searchFor, #sitesearchrh, #siteSearchWelcome").toggle();
    $(".GEGRating").toggle();
}



function doSiteSearch() 
{
    location.href = "Search.aspx?searchterm=" + escape($("#sitesearchtextbox").val()); 
   
}

function ActivateSiteSearch_V1() {



    //popSearchvar htm = "<div id='popSearch'>Search for <input type='text' id='sitesearchtextbox' /><input type='button' value='Go' id='sitesearchgo' /></div>";
    //$("#searchTab, #popSearch").show();
   // $("#searchTab").html(htm);
    //$("#topNav").before(htm);
   // $("#sitesearchgo").click(function() { location.href = 'Search.aspx?searchterm=' + $("#sitesearchtextbox").val(); });


    //$('#searchToggle').click(function() {
  //      $('#popSearch').slideToggle("slow");
   //     var src = ($(this).attr("src") === "images/uksp/searchTab.png")
  //                      ? "images/uksp/searchTab_on.png"
  //                      : "images/uksp/searchTab.png";
  //      $(this).attr("src", src);
 //   });
//

}