﻿// Job search page js

    
    // closes popup shown via serverside code informing user if the job link no longer exists 
    function CloseModalNoLinkPopup()
    {
	    ShowHideObj("NoJobLinkPopup","hidden");
	    ShowHideObj("ModalBg","hidden");
    }

    
    // user help messages
    var LocationHelpTip = "<div class='ItemInfoCloseBtnWrapper' style='border:0px;'><input type='button' value='X' class='GreenInputButtonStyle' /></div><h6>Location Help Tip</h6><p style='clear:left;'>Enter City/Town name here. If you are looking for Offshore work, then type Offshore here. If you are happy to work in any location, leave this location box empty.</p><p>You can search muiltiple locations by seperating each location with a comma e.g. Aberdeen, Edinburgh, Offshore will match job vacancies in Aberdeen or Edinburgh or Offshore.</p><p><strong>Note:</strong> Entering quotes around location names and using ' or ' / ' and ' keyword logic is not required/supported (Do not type 'OR' / 'AND' between location keywords).</p>";
    var JobTitleHelpTip = "<div class='ItemInfoCloseBtnWrapper' style='border:0px;'><input type='button' value='X' class='GreenInputButtonStyle' /></div><h6>Job Title Help Tip</h6><p style='clear:left;'>Enter Job Title / Profession Title here.</p><p>You can search on full job titles e.g. Software Developer or on words contained in the job title e.g. just typing software will return all jobs with software in their job title.</p><p>You can search muiltiple Job Titles / Job Title keywords by seperating each title/keyword with a comma e.g. Software, Web, ASP Developer will match job titles containing Software or Web or ASP Developer.</p><p><strong>Note:</strong> Entering quotes around Job Titles and using ' or ' / ' and ' keyword logic is not required/supported (Do not type 'OR' / 'AND' between location keywords).</p>";
    var KeywordsHelpTip = "<div class='ItemInfoCloseBtnWrapper' style='border:0px;'><input type='button' value='X' class='GreenInputButtonStyle' /></div><h6>Job Description Keywords Help Tip</h6><p style='clear:left;'>Enter Job Description keywords here e.g. skills keywords, qualification keywords, role or responsibility keywords etc e.g. technical lead, team lead. Our system will return any vacancies containing the keyword(s) you have entered in their job description.</p><p>You can search on muiltiple keywords by seperating each keyword with a comma - you then specify if the job description must contain All or Any of these keywords by selecting the 'Find Any Keyword' or 'Find all Keywords' tick box located under the Keywords input box.</p><p><strong>Note:</strong> Entering quotes around job description keywords and using ' or ' / ' and ' keyword logic is not required/supported (Do not type 'OR' / 'AND' between location keywords).<p>";
 
    // global variables related to display of job
    
    var CurrentlyViewingJobTitle = "";
    var CurrentJobDetailId = "";
    var JobId = 0; // default 0 = no ids yet set
    var JobPopH = 500; // default 500
    var CachedItemIdsArray = new Array();
    var SearchInProgress = false;
    
    var CachedViewedJobsLimit = 51;  // last 50 viewed jobs stored in viewed jobs list
    
    // Apply btns image preload
    var applyBtnOver = new Image();
    var applyBtn= new Image();
    applyBtn.src = "Navigation/NavButtonApplyForJob.png" ;
    applyBtnOver.src = "Navigation/NavButtonApplyForJobOver.png";
 
 
 // ================== RUN JOB SEARCH / DISPLAY SEARCH RESULTS ================================
    
    function SearchBtnClick()
    {
        GoToPage = 1;
        
        FetchSearchResults();
    }
    
    function AjaxGetData()
    {
        // get paging parameters via calls to get functions defined in Scripts/Ajax/AjaxGridAndPager.js
      //    var paramSortExpression = _getSortExpression();
//	        var paramSortField = _getCurrentSortField();
//	        var paramSortDirection = _getSortDirection();
//	        var paramSortDivId = _getSortDirectionDiv();
	        
        var vacancyTypeListValue = GetControlValue("VacancyTypeList");    //   GetListSelectedValues("VacancyTypeList");  // any test
        var countryListSelectedValue = GetControlValue("CountryList");    //GetListSelectedValues("CountryList");    // any
        var postedWithinNumDays = GetListSelectedValues("PostedWithinList");  
        var sortByListValue = GetListSelectedValues("SortByList"); //"RANK DESC";
        var location = document.getElementById("LocationTxtbox").value.Trim();
        var jobTitle =  document.getElementById("JobTitleTxtbox").value.Trim();
        var keywordsFromTextarea = document.getElementById("KeywordsTextArea").value.Trim();
        var boolAnyKeywords = document.getElementById("AnyKeywordsCheckbox").checked;  
        var boolAllKeywords = document.getElementById("AllKeywordsCheckbox").checked;
        var startPageNumber = GoToPage;
        var pageSize = 17;
        
        if( countryListSelectedValue == "0" )
        {
            countryListSelectedValue = "";
        }

        // added 3/06/09 - if skills keywords added and neither any or all keywords checkboxes are ticked, tick any keywords checkbox as default setting
        if (keywordsFromTextarea != "" && boolAnyKeywords == false && boolAllKeywords == false) 
        {
            boolAnyKeywords = true;
            document.getElementById("AnyKeywordsCheckbox").checked = true;        
        }
        
       // DisplayHideObj("CancelSearchInfo","block");  // new
        //alert("industryListValue = " + industryListValue + "\n vacancy type list = " + vacancyTypeListValue + "\n countryListSelectedValues =  " + countryListSelectedValues + " \n postedWithinNumDays = " + postedWithinNumDays + "\n sortByListValue = " + sortByListValue);
       
        ShowHideAnimatedMsgBox("visible","Searching Jobs");
	    //DisplayHideObj("SearchingMessage","block");//new
        //DisableEnableSearchElements(true);  // new
        SearchInProgress = true;
        PageMethods.GetSearchResults(vacancyTypeListValue, countryListSelectedValue, postedWithinNumDays, location, jobTitle, keywordsFromTextarea, boolAnyKeywords, boolAllKeywords, startPageNumber, pageSize, sortByListValue, JobSearchCompletedHandler, SearchRequestError, 'Vacancy Search');
    
    }
   
    
    var HtmlResponse = "";
    
    function JobSearchCompletedHandler(responseHtml,context)
    {
        SearchInProgress = false;
       // DisableEnableSearchElements(false);//new
	   // DisplayHideObj("CancelSearchInfo","none");//new
	   // DisplayHideObj("SearchingMessage","none");//new
        ShowHideAnimatedMsgBox("hidden","");
        document.getElementById("IntroTextWrapper").style.display = "none";
        document.getElementById("SearchResultsWrapper").innerHTML = responseHtml;
        document.getElementById("SearchResultsWrapper").style.display = "block";
        
        ShowHidePagingContextMenu();
    }
    
    function ShowHidePagingContextMenu()
    {
         // added 17/6/08 to dynamically display or hide custom right click menu paging options
        var _numPages = document.getElementById("txtTotalRows").value.Trim();
        //alert(_numPages);
        
        if( _numPages != "")
        {
            if(parseInt(_numPages) > 0)
            {
                DisplayHideObj("ContextMenuPaging","block");
            }
            else
            {
                DisplayHideObj("ContextMenuPaging","none");
            }
        }
        else
        {
            DisplayHideObj("ContextMenuPaging","none");
        }
    }
    
    
    function CancelSearch()
    {
        SearchInProgress = false;
        DisableEnableSearchElements(false);
        DisplayHideObj("SearchingMessage","none");
    }
    
    
// ====================== SHOW JOB INFO POPUP RELATED CODE ============================

    
    function ShowJob(id,jobTitle, jobDetailsDivId, addToList, location)
    {
        if (PageLoadCompleted == true) {
            CurrentJobDetailId = jobDetailsDivId;
            JobId = id;
            CurrentlyViewingJobTitle = jobTitle;
            document.title = "Qedi Job Search : " + jobTitle;

            if (HashBookmarkSupport == true) {
                window.location.hash = id;
            }

            document.getElementById("JobDescriptionWrapper").innerHTML = "";

            HorizontallyCenterDiv("ViewJobPopup", 674, 20)
            ShowHideObj("JobPopupModalBg", "visible");

            // calculate height as Available height - 60px;
            GetAvailableDisplayArea();
            JobPopH = DisplayAreaHeight - 80;
            // alert("pop h = " + JobPopH);
            DisplayHideObj("JobDescriptionScrollWrapper", "none");

            // if this job id exists in AppliedForJobsArray show AlreadyAppliedMessage
            var applied = jobAppliedFor(id);

            if (applied == true) {
                DisplayHideObj("AlreadyAppliedMessage", "block");
                // EnableDisableObj("ApplyBtn",true);
            }
            else {
                DisplayHideObj("AlreadyAppliedMessage", "none");
                //EnableDisableObj("ApplyBtn",false);
            }

            // size, add text and display
            var jobInfoHtml = document.getElementById(CurrentJobDetailId).innerHTML;

            // SET jobDescriptionScrollWrapper height
            var headerBarOffsetHeight = document.getElementById("ViewJobHeaderBar").offsetHeight + 33; // (+33 for top row corner)
            var appliedMsgOffsetHeight = document.getElementById("AlreadyAppliedMessage").offsetHeight;
            var scrollH = JobPopH - (headerBarOffsetHeight + appliedMsgOffsetHeight);

            document.getElementById("JobDescriptionScrollWrapper").style.height = scrollH + "px";
            document.getElementById("JobPreviewMenuWrapper").style.height = scrollH + "px";
            DisplayHideObj("JobDescriptionScrollWrapper", "block");
            document.getElementById("JobDescriptionWrapper").innerHTML = jobInfoHtml;

            if (IsLessIE7 == true) {
                ShowHidePageLists("hidden");
            }

            // added 17 june - show context menu job detail popup options section
            DisplayHideObj("ContextMenuPopup", "block");

            // add job to viewed jobs list   
            if (addToList == true) {
                // CHECK if item already cached - if so do not add div id html again!
                var isCachedItem = isItemCached();
                if (isCachedItem == false) {
                    var nextOptionIndex = document.getElementById("ddlViewedJobs").length;

                    if (nextOptionIndex >= CachedViewedJobsLimit) {
                        nextOptionIndex = RemoveCachedJobAtListIndexOne();
                    }

                    var listText = jobTitle + " (" + location + ")";
                    var opt = new Option(listText, id);
                    document.getElementById("ddlViewedJobs").options[nextOptionIndex] = opt;

                    // add item id to cached item ids
                    CachedItemIdsArray.push(JobId);

                    // VERSION 1 innerHTML based : copy job info div with new div id into cache area
                    // var cachedDiv = '<div id="CachedJob' + JobId + '" class="cachedDiv">' + jobInfoHtml + '</div>';
                    // document.getElementById("JobCachingWrapper").innerHTML += cachedDiv;

                    // VERSION 2 (using DOM addChild method - more efficient than version 1)
                    var cachedJobWrapperRef = document.getElementById("JobCachingWrapper");
                    var newCachedDiv = document.createElement('div');
                    var divId = "CachedJob" + JobId;
                    newCachedDiv.setAttribute('id', divId);
                    newCachedDiv.setAttribute('class', 'cachedDiv');
                    newCachedDiv.innerHTML = jobInfoHtml;
                    cachedJobWrapperRef.appendChild(newCachedDiv);
                }
                //else { alert("Not added. ALREADY CACHED"); } // TESTING
            }

            SetPopupYpos("ViewJobPopup", 20);

            // show job detail popup div
            ShowHideObj("ViewJobPopup", "visible");
        }
        else  // page has not yet finished loading in
        {
            ShowHideOkMsgBox("visible", "<p><b>Please wait a few moments while the page finishes loading.</b><br /><br />After the page has finished loading, click on any Job to view full details.</p>");
        }
    }
    
    
   
   function isItemCached()
   {
        var isAlreadyCached = false;
        var cacheArrayLength = CachedItemIdsArray.length;
        for(i=0; i < cacheArrayLength; i++)
        {
            if(CachedItemIdsArray[i] == JobId)
            {
                isAlreadyCached = true;
            }
        }
        return isAlreadyCached;
   }
   
   
   
// REMOVES VIEWED / CACHED JOB at index 1 IN VIEWED FREELANCER LIST
// (Called when viewed job list reaches maximum size of 50 jobs. Each time a new job is
// viwed after list reaches 51 items, job at list index 1 is removed and new viewed job is added 
// to end of list)

function RemoveCachedJobAtListIndexOne()
{
    // remove first viewed freelancer's id from CachedItemIds array
    var firstId = CachedItemIdsArray.shift();
    //alert("firstId removed = " + firstId);

    // remove first freelancer in list from dropdown list
    document.getElementById("ddlViewedJobs").remove(1);
    
    // remove freelancers associated info div from CachedJob div wrapper
    var d = document.getElementById('JobCachingWrapper');  // note JobCachingWrapper is id of div wrapping stored viewed freelancer info divs
    var removeDiv = document.getElementById("CachedJob"+firstId);
    d.removeChild(removeDiv);  
    
    var newOptionsArrayLength = document.getElementById("ddlViewedJobs").length;
    
    return newOptionsArrayLength;        
}
   
   
    function CloseJobPopup()
    {
           // if( HashBookmarkSupport == true ){window.location.hash = "";}
            ShowHideObj("ViewJobPopup","hidden");
            ShowHideObj("JobPopupModalBg","hidden");
            if(IsLessIE7 == true)
            {
                ShowHidePageLists("visible");
            }
            DisplayHideObj("ContextMenuPopup","none");
    }
    

// ================== TOGGLE CHECKBOX SELECTION =================================

    function SelectCheckbox( selectObj, deselectObj1, deselectObj2 )
	{
		document.getElementById( selectObj ).checked = true;
		document.getElementById( deselectObj1 ).checked = false;
		document.getElementById( deselectObj2 ).checked = false;
	}
    

// =================== ACCOMODATE PAGE SCROLL OFFSET =============================
    
    // set all (to accomodate any of them currently being displayed) popup style divs top pos on scroll
    
    function SetPopupDivsYpos()
    {
        SetPopupYpos("ViewJobPopup", 20); // function defined in universal.js
        SetPopupYpos("sendToFriendWrapper", 150);
		//SetSendToYpos();  // defined in SendToFRiend.js
    }
    
  window.onscroll = SetPopupDivsYpos;
 
 
 
 // =================== HIDE MODAL BG AND ANY POPUP DIVS =========================
 
 function CloseModalBgAndAllPopupDivs()
 {
        ShowHideObj("ModalBg","hidden");
        CloseJobPopupModalBg(); 
        OpenCloseSavePopup('hidden');
        if(IsLessIE7 == true)
            {
                ShowHidePageLists("hidden");
            }
    // add additional divs e.g. send to friend etc here
 }
 
 
 function CloseJobPopupModalBg()
 {
        ShowHideObj("JobPopupModalBg","hidden");
        //if( HashBookmarkSupport == true ){window.location.hash = "";} 
        ShowHideObj("ViewJobPopup","hidden"); // function defined in universal.js
        if(IsLessIE7 == true)
            {
                ShowHidePageLists("hidden");
            }
       // added 17 june - hide context menu job detail popup options section
        DisplayHideObj("ContextMenuPopup","none");
 }
 
  
 // =========================== APPLY FOR JOB ======================================
 
 
 var SendingApplication = false;  // flag to limit to 1 job application request at a time?
 
 function Apply()
 {
    //alert("apply for job id = " + JobId);//tesr
    if(LoggedInUser == true)
    {
        // clientRef and forwardTo not relevant to Qedi at this stage so set to empty strings
       var clientRef = ""; // not utilised by qed go resourcing system  //GetControlValue("txtClientRef" + JobId);
       var forwardTo = ""; // not utilised by qed go resourcing system  //GetControlValue("txtForwardApplicationToEmail" + JobId);

       ShowHideAnimatedMsgBox("visible", "Sending Job Application");
       PageMethods.ApplyForVacancy(JobId, CurrentlyViewingJobTitle, JobApplicationRequestCompleted, UpdateRequestError, JobId);
    }
    else
    {
       ShowHideOkMsgBox("visible",'You must <a href="#" onclick="RedirectToLogin();return false;">Login</a> / <a href="Register.aspx">Register</a> to use this feature!');
    }
 }


 function JobApplicationRequestCompleted(responseHtml, context) 
 {
     ShowHideAnimatedMsgBox("hidden", "");
     ShowHideOkMsgBox("visible", responseHtml);

    // if job application request successful then push id of applied for job into applied for jobs array
     if (responseHtml.indexOf("Job Application Sent") != -1)
     {
         AppliedForJobsArray.push(context);
         CloseJobPopup();
     }
     
 }
 
 // LOOPS AppliedForJobsArray and returns true if a job id exists in array matching passed parameter
    
    function jobAppliedFor(job_id)
    {
        var alreadyApplied = false;
         
        for(i=0; i < AppliedForJobsArray.length; i++)
        {
            if(job_id == AppliedForJobsArray[i])
            {
                alreadyApplied = true;
                break;
            }
        }
        
        return alreadyApplied;
    }
 
 
 // =================== AJAX MESSAGE BAR RELATED CODE ==============================
 
// function autoCloseAjaxMsgBar()
// {
//     //FadeOpacity("AjaxUpdateMessageBar", 100, 0, 25, true);
//     // $("#AjaxUpdateMessageBar").fadeOut("normal");
//     
//     CloseModalMsgBox();  // NOTE: INSTEAD OF AJAX MSG BAR WE ARE NOW USING NORMAL MODAL MSG BOX 23/05/09
// }

 
//  ============================== STORE JOB ========================================
 
  function StoreJob()
 {
    if(LoggedInUser == true)
    {
       //document.getElementById("AjaxUpdateMessageBar").innerHTML = "Storing Job ...";
        //       SetObjectOpacity("AjaxUpdateMessageBar",100);
       //       ShowHideObj("AjaxUpdateMessageBar","visible");

       ShowHideAnimatedMsgBox("visible", "Storing Job");
       PageMethods.StoreJob(JobId,StoreJobRequestCompleted,DataRequestError,JobId);
    }
    else
    {
       ShowHideOkMsgBox("visible",'You must <a href="#" onclick="RedirectToLogin();return false;">Login</a> / <a href="Register.aspx">Register</a> to use this feature!');
    }
 }


 function StoreJobRequestCompleted(responseHtml, context) 
 {
     ShowHideAnimatedMsgBox("hidden", "");
     
    if( responseHtml.indexOf("Job Stored") != -1 )
    {
//        SetObjectOpacity("AjaxUpdateMessageBar",100);
//        ShowHideObj("AjaxUpdateMessageBar", "visible");
//        document.getElementById("AjaxUpdateMessageBar").innerHTML = responseHtml;
        //        setTimeout("autoCloseAjaxMsgBar()",4000);

        // add new saved job to drop down list
        var listRef = document.getElementById("ddlStoredJobsList");
        var nextOptionIndex = listRef.length;
        var newOption = new Option(CurrentlyViewingJobTitle,JobId);
        listRef.options.add(newOption,nextOptionIndex);
        
        // add new job div html into stored job wrapper div
        var jobDivWrapperId = "CachedJob" + context;
        var jobInfoHtml = document.getElementById(jobDivWrapperId).innerHTML; 
    
    // copy job div html into stored job cache area
        var cachedDiv = '<div id="StoredJob' + JobId + '" class="cachedDiv">' + jobInfoHtml + '</div>';
        document.getElementById("StoredJobCachingWrapper").innerHTML += cachedDiv;
          
    }
//    else
//    {
//        //autoCloseAjaxMsgBar();
//        ShowHideOkMsgBox("visible",responseHtml);
//    }

    ShowHideOkMsgBox("visible", responseHtml);
 }
 


// ====================== VIEWED JOBS LIST INDEX CHANGED ===========================

function ViewedJobsListChange()
{
    var listRef = document.getElementById("ddlViewedJobs");
    var indx = listRef.selectedIndex;
    if(indx > 0)
    {
        var jobid = listRef.options[indx].value;
        var jobDesc = listRef.options[indx].text;
        var divid = "CachedJob" + jobid;
        listRef.selectedIndex = 0;
        ShowJob(jobid , jobDesc , divid, false, "");
    }
}



// =================== STORED JOB LIST CHANGE / VIEW STORED JOB ====================

function StoredJobListChange()
{
    var listRef = document.getElementById("ddlStoredJobsList");
    var indx = listRef.selectedIndex;
    
    if(indx > 0)
    {
        var jobid = listRef.options[indx].value;
        var jobDesc = listRef.options[indx].text;
        var divid = "StoredJob" + jobid;
        listRef.selectedIndex = 0;
        ShowJob(jobid , jobDesc , divid, false, "");
    }
    
}


// ======================== SAVE SEARCH CRITERIA TO COOKIE ON EXIT ==========================


// ------------------ reset search criteria controls ---------------

function ResetSearchCriteria()
{
    document.getElementById("VacancyTypeList").selectedIndex = 0;
    document.getElementById("CountryList").selectedIndex = 0;    // any
    document.getElementById("PostedWithinList").selectedIndex = 0;  
    document.getElementById("SortByList").selectedIndex = 0;
    document.getElementById("LocationTxtbox").value = "";
    document.getElementById("JobTitleTxtbox").value = "";
    document.getElementById("KeywordsTextArea").value = "";
    document.getElementById("AnyKeywordsCheckbox").checked = true;  
    document.getElementById("AllKeywordsCheckbox").checked = false;
}


// --------------- save and restore page state --------------------

function SaveSearchToCookie()
{
    if(SaveSearchCriteriaToCookie == true)
    {
        //var industryListValue = GetListSelectedValues("IndustryList");
        var vacancyTypeListValue = GetListSelectedValues("VacancyTypeList");  // any test
        var countryListSelectedValues = GetListSelectedValues("CountryList");    // any
        var postedWithin = GetListSelectedValues("PostedWithinList");  
        var sortBy = GetListSelectedValues("SortByList");
        var location = document.getElementById("LocationTxtbox").value.Trim();
        var jobtitle =  document.getElementById("JobTitleTxtbox").value.Trim();
        var keywords = document.getElementById("KeywordsTextArea").value.Trim();
        var boolAnyKeywords = document.getElementById("AnyKeywordsCheckbox").checked;
        var boolAllKeywords = document.getElementById("AllKeywordsCheckbox").checked;
        var showHelp = "";
        if (document.getElementById("chkShowHelp").checked == true) { showHelp = "1"; }

        //var cookieString = industryListValue + "^" + countryListSelectedValues + "^" + location + "^" + vacancyTypeListValue + "^" + jobtitle + "^" + keywords + "^" + boolAnyKeywords + "^" + boolAllKeywords + "^" + postedWithin + "^" + sortBy;
        var cookieString = countryListSelectedValues + "^" + location + "^" + vacancyTypeListValue + "^" + jobtitle + "^" + keywords + "^" + boolAnyKeywords + "^" + boolAllKeywords + "^" + postedWithin + "^" + sortBy + "^" + showHelp;
        
        //SetCookieWithDate("JobSearchCookie", cookieString,1);
        
        SetCookie("JobSearchCookie",cookieString); // expire on close while developing
    }
}


window.onbeforeunload = SaveSearchToCookie;


// =========================== EMAIL JOB LINK =============================

function SendPageLink(friendsEmail,sendersEmail,jobLinkUrl)
{
    PageMethods.EmailJobLink(friendsEmail,sendersEmail,jobLinkUrl,JobId);
    ShowSendingPageLinkMessage();   // defined in SendPageLink.js
}


// ======================== SAVE SEARCH CRITERIA ===============================
    
function OpenCloseSavePopup(vis)
{
    document.getElementById("txtSaveSearchTitle").value = "";
    DisplayHideObj("searchTitleVal","none");
    ShowHideObj("ModalBg",vis);
    ShowHideObj("SaveSearchPopup",vis);
    
    if(vis == "visible")
    {
        document.getElementById("txtSaveSearchTitle").focus();
    }
}

    
function SaveSearchBtnClick()
{
    DisplayHideObj("searchTitleVal","none");
    var title = "";
    
    if(LoggedInUser == true)
    {
        title = document.getElementById("txtSaveSearchTitle").value.Trim();
        if(title == "")
        {
            DisplayHideObj("searchTitleVal","block");
        }
        else  // valid
        {
            EnableDisableObj("SaveSearchBtn",true);
           // var industryListValue = GetListSelectedValues("IndustryList");
            var vacancyTypeListValue = GetListSelectedValues("VacancyTypeList");  // any test
            var countryListSelectedValues = GetListSelectedValues("CountryList");    // any
            var postedWithin = GetListSelectedValues("PostedWithinList");  
            var sortBy = GetListSelectedValues("SortByList"); //"RANK DESC";
            var location = document.getElementById("LocationTxtbox").value.Trim();
            var jobtitle =  document.getElementById("JobTitleTxtbox").value.Trim();
            var keywords = document.getElementById("KeywordsTextArea").value.Trim();
            
            var boolAnyKeywords = 0;
            if(document.getElementById("AnyKeywordsCheckbox").checked == true)
            { boolAnyKeywords = 1; }
              
            var boolAllKeywords = 0;
            if( document.getElementById("AllKeywordsCheckbox").checked == true)
            { boolAnyKeywords = 1; }

            var xml = '<?xml version="1.0" encoding="iso-8859-1"?><searchCriteria><item id="CountryList" type="text">' + countryListSelectedValues + '</item><item id="LocationTxtbox" type="text">' + location + '</item><item id="VacancyTypeList" type="text">' + vacancyTypeListValue + '</item><item id="JobTitleTxtbox" type="text">' + jobtitle + '</item><item id="KeywordsTextArea" type="text">' + keywords + '</item><item id="AnyKeywordsCheckbox" type="checkbox">' + boolAnyKeywords + '</item><item id="AllKeywordsCheckbox" type="checkbox">' + boolAllKeywords + '</item><item id="PostedWithinList" type="list">' + postedWithin + '</item><item id="SortByList" type="list">' + sortBy + '</item></searchCriteria>';
                    
           //  ShowHideOkMsgBox(xml,"visible");  // test
             
           // var searchTitle = "Test save";// document.getElementById("txtSaveSearchTitle").value.Trim();
            
           // DisplayHideObj("SavingSearchMsg","block");
            PageMethods.SaveSearch(xml,title,SaveSearchRequestCompleted,DataRequestError,title);
        }
    }
    else
    {
        ShowHideOkMsgBox("visible",'You must <a href="#" onclick="RedirectToLogin();return false;">Login</a> / <a href="Register.aspx">Register</a> to use this feature!');
    }
}


// note: context param is search title

function SaveSearchRequestCompleted(response,context)
{
    var splitResponse = response.split("$");
    var msg = splitResponse[0];

    OpenCloseSavePopup('hidden');
    EnableDisableObj("SaveSearchBtn",false);

    ShowHideOkMsgBox("visible", msg);
    
    if(response.indexOf('Job Search Criteria Saved') != -1)
    {
//        SetObjectOpacity("AjaxUpdateMessageBar",100);
        //        ShowHideObj("AjaxUpdateMessageBar","visible");

       // $("#AjaxUpdateMessageBar").fadeIn("normal");
      //  document.getElementById("AjaxUpdateMessageBar").innerHTML = msg;
            
        if(splitResponse.length > 1)
        {
         // add item to saved search list
            var nextOptionIndex = document.getElementById("ddlSavedSearchList").length;
            var opt = new Option(context,splitResponse[1]);
            document.getElementById("ddlSavedSearchList").options[nextOptionIndex] = opt;  
        }
        
       // setTimeout("autoCloseAjaxMsgBar()",4000);
    }
//    else        //if(response.indexOf("Search Save Failed") != -1)
//    {
//        autoCloseAjaxMsgBar();
//        ShowHideOkMsgBox("visible",msg);
//    }
    
}



// ======================== RESTORE SAVED SEARCH CRITERIA =======================
    
// -------------- saved search list index changed ---------

function SavedSearchListChange()
{
    var listRef = document.getElementById("ddlSavedSearchList");
    var indx = listRef.selectedIndex;

    if(indx > 0)
    {
        var searchid = listRef.options[listRef.selectedIndex].value;
        listRef.selectedIndex = 0;
        DisableEnableSearchElements(true);
        DisplayHideObj("RestoringMessage","block");
        PageMethods.GetSavedSearchXml(searchid,RestoreSavedSearch,DataRequestError);
    }
}


    function RestoreSavedSearch(xmlDoc)
    {       
         DisableEnableSearchElements(false);
          DisplayHideObj("RestoringMessage","none");
            var testMsg = "";
            var itemNodeText = "";
           // var restoreMsg = "<b>Report Restored!</b><br />Press Run Report button to run restored Report."; // assumes succesful restore
            
            if(xmlDoc.documentElement.nodeName == "message")    // error occurred
            {
                ShowHideOkMsgBox("visible",xmlDoc.documentElement.text.Trim()); //alert( "error while parsing");
            }
            
            else    // Parse xml search criteria and restore
            {
                var itemNodesCollection = xmlDoc.documentElement.getElementsByTagName("item");
                
                for( var i = 0; i < itemNodesCollection.length; i++ )
                {
                  var itemNode = itemNodesCollection.item( i );
                  var itemNodeId = itemNode.getAttribute('id').toString();
                  
                  if(IsIE == true)
                  {
                     itemNodeText = itemNode.text.Trim();
                  }
                  else
                  {
                     itemNodeText = itemNode.textContent.Trim();    //itemNode.firstChild.nodeValue;
                  }
                  
                  var objref = document.getElementById(itemNodeId);
                  var objrefType = itemNode.getAttribute('type').toString();  // Updated 22/06/07 to read saved object type property os we can now identify popup saves objref.type;
                  
                 // TEST WRITE OUTPUT TO TEXT AREA
                 //testMsg += "item type = " + objrefType + " item Node text = " + itemNodeText + "  and id=" + itemNodeId + "\n";
                  
                  //alert("object type = " + objref.type);
                  //testMsg += "\n Object type = " + objrefType;
                  
                  if(objrefType == "text")   // Restore Textbox value
                  {
                       objref.value = itemNodeText;
                  }
                  
                  else if(objrefType == "list")     // "select-one")   // Restore List Selection
                  {
                        // Loop list object and read option values - if option value matches restore value 
                        // set selected list item to show restored value
                        SetListIndexForValue(itemNodeId,itemNodeText);    
                  }
                  
                  else if(objrefType == "checkbox" || objrefType == "radio" )   // restore checkbox or radio btn selection
                  {
                      if(itemNodeText == "1")
                      { objref.checked = true;} else { objref.checked = false; }
                  }

                  // execute AjaxGetData to load restored search results
                  GoToPage = 1;
                  AjaxGetData();
                  
                }  // end for loop
                
               
                
                // TESTING output write
                //document.getElementById("debugarea").value = testMsg;
                          

            }  // end restore else block
    }
   
   
   // =================================== DISABLE SEARCH ELEMENTS  ===============================
   
     var SearchElementsArray = new Array("SaveSearchBtn","VacancyTypeList","CountryList","PostedWithinList","SortByList","LocationTxtbox","JobTitleTxtbox","KeywordsTextArea","AnyKeywordsCheckbox","AllKeywordsCheckbox");
     
   function DisableEnableSearchElements(boolDisable)
   {
        for(i=0; i < SearchElementsArray.length; i++)
        {
            EnableDisableObj(SearchElementsArray[i],boolDisable);
        }
   }
      

// ============================= HOVER TIPs ===========================

function RunSearchHoverTip()
{
    if(SearchInProgress == true)
    {
        //DisplayTip(tipText, tipWidth, moveWithMouse)
    }
}

    function ContextShowHideHelpBox()
    {
        if(document.getElementById("HelpBoxWrapper").style.visibility == "hidden")
        {
            ShowHideHelpBox("visible");
            document.getElementById("ContextHelp").innerHTML = "Close Help";
        }
        else
        {
            ShowHideHelpBox("hidden");
            document.getElementById("ContextHelp").innerHTML = "Open Help";
        }
    }

  
  function ShowHideHelpBox(vis)
  {
        HorizontallyCenterDiv("HelpBoxWrapper", 610, 10);
        
        if( document.getElementById("HelpBoxText").innerHTML.Trim() == "")
        {
            var helpText = document.getElementById("HelpInfoTextWrapper").innerHTML;
            document.getElementById("HelpBoxText").innerHTML = helpText;
        }
        
        var listVis = "visible";
        if(vis == "visible") { listVis = "hidden"; }
        
        if(IsLessIE7 == true)
        {
            ShowHidePageLists(listVis);
        }
        
        if(vis == "visible")
        {
            document.getElementById("ContextHelp").innerHTML = "Close Help";
        }
        else
        {
            document.getElementById("ContextHelp").innerHTML = "Open Help";
        }
        
        ShowHideObj("ModalHelpBg",vis);
        ShowHideObj("HelpBoxWrapper",vis);
  }
  
  var FocusHelpTipBg = "#57bcde";
  
  function ShowFocusHelpTip(tiptext,tipwidth,xpos,ypos,controlid) 
  {
      if (document.getElementById("chkShowHelp").checked == true) 
      {
          document.getElementById(controlid).style.backgroundColor = FocusHelpTipBg;
          GetAvailableDisplayArea();

          var x = parseInt(DisplayAreaWidth / 2.3);
          FocusTip(tiptext, tipwidth, x, ypos);
      }
  }

  function HideFocusHelpTip(controlid) 
  {
      if (document.getElementById("chkShowHelp").checked == true) 
      {
          document.getElementById(controlid).style.backgroundColor = "#ffffff";
          HideTip();
      }
  }
  
  
// directs user to login page + query string param so they are redirected back to the job they are
// currently viewing after they have logged in

function RedirectToLogin()
{
//    TO DO : change to absolute https URL
    top.location.href = "https://jobs.qed-i.com/Login.aspx?jobid=" + JobId;
}



function AnyAllKeywordsCheckboxClicked(clickedCheckboxId, otherCheckboxId) 
{
    if (document.getElementById(clickedCheckboxId).checked == true) 
    {
        if (document.getElementById(otherCheckboxId).checked == true) 
        {
            document.getElementById(otherCheckboxId).checked = false;
        }
    }
}




// ------------- SAVE JOB NOTIFICATION RELATED FUNCTIONALITY ----------------


var JobNotificationHighlightColour = "#ffffcc";

function OpenJobNotificationPopupBtnClick() {
    HorizontallyCenterDiv("JobNotificationPopup", 520, 20);
    //    GetAvailableDisplayArea();
    //    var popup_x = parseInt(DisplayAreaWidth / 2.3);
    //    document.getElementById("JobNotificationPopup").style.left = popup_x + "px";

    // SetObjBgColour("LocationTxtbox", JobNotificationHighlightColour);
    // SetObjBgColour("txtJobTitleJobAlert", JobNotificationHighlightColour);
    // SetObjBgColour("ddlCountryJobAlert", JobNotificationHighlightColour);
    // SetObjBgColour("ddlVacancyTypeJobAlert", JobNotificationHighlightColour);

    // pre populate criteria with any criteria user has entered in job search criteria panel

    if (GetControlValue("JobTitleTxtbox") != "")
    { document.getElementById("txtJobTitleJobAlert").value = GetControlValue("JobTitleTxtbox"); }

    var selVacancyTypeId = GetControlValue("VacancyTypeList");
    SetListIndexForValue("ddlVacancyTypeJobAlert", selVacancyTypeId);

    var selCountryId = GetControlValue("CountryList");
    if (selCountryId == "") { selCountryId = 0; }
    SetListIndexForValue("ddlCountryJobAlert", selCountryId);

    // show popup  
    ShowHideObj("JobNotificationPopupModalBg", "visible");
    ShowHideObj("JobNotificationPopup", "visible");
    $("#JobNotificationPopup").fadeIn("normal");

}


function CloseJobNotificationPopup() {
    SetObjBgColour("ddlVacancyTypeJobAlert", "#ffffff");
    SetObjBgColour("txtJobTitleJobAlert", "#ffffff");
    SetObjBgColour("ddlCountryJobAlert", "#ffffff");

    ShowHideObj("JobNotificationPopupModalBg", "hidden");

    $("#JobNotificationPopup").fadeOut("normal");
    ShowHideObj("JobNotificationPopup", "hidden");
    DisplayHideObj("SaveJobMatchResponseMessage", "none");
}


function SaveJobNotificationBtnClick() {
    if (LoggedInUser == false) {
        ShowHideOkMsgBox("visible", 'You must <a href="#" onclick="RedirectToLogin();return false;">Login</a> / <a href="Register.aspx">Register</a> to use this feature!');
    }
    else {
        var notificationValidationMsg = "";
        // ensure no validation background colour highlights on email and mobile number input boxes
        SetObjBgColour("txtJobNotificationEmail", "#ffffff");
        SetObjBgColour("txtJobNotificationMobileNumber", "#ffffff");

        // set boxes back to job notificaton highlight colour as we may have highlighted them in strong yellow (#ffff00) on previous validation request).
        //SetObjBgColour("LocationTxtbox", JobNotificationHighlightColour);
        SetObjBgColour("txtJobTitleJobAlert", "#ffffff");
        SetObjBgColour("ddlCountryJobAlert", "#ffffff");
        SetObjBgColour("ddlVacancyTypeJobAlert", "#ffffff");
        SetObjBgColour("txtJobMatchNotificationName", "#ffffff");

        var emailChecked = document.getElementById("chkEmail").checked;
        var textMsgChecked = document.getElementById("chkTextMessage").checked;
        var email = GetControlValue("txtJobNotificationEmail");
        var mobileNum = GetControlValue("txtJobNotificationMobileNumber");
        var mobileCountryCodePrefix = GetControlValue("ddlMobileNumberCountry");
        var jobMatchNotificationName = GetControlValue("txtJobMatchNotificationName");

        //if user has entered a alert email address ensure notify by email checkbox is ticked
        if (email.Trim() != "") { document.getElementById("chkEmail").checked = true; emailChecked = true; }

        // if user has entered a text alert mobile number ensure notify by text message checkbox is ticked
        if (mobileNum.Trim() != "") { document.getElementById("chkTextMessage").checked = true; textMsgChecked = true; }

        var vacancyTypeId = GetControlValue("ddlVacancyTypeJobAlert");
        if (vacancyTypeId == "") { vacancyTypeId = 0; }

        var countryId = GetControlValue("ddlCountryJobAlert");
        var jobTitle = GetControlValue("txtJobTitleJobAlert");
        //var location = GetControlValue("LocationTxtbox");

        if (countryId == "0" && jobTitle == "" && vacancyTypeId == 0) {
            notificationValidationMsg = "<li><b>You have not entered any Job Match Criteria!</b><br /><br /><span style=\"background-color:#ffff00;color:#333333\">Please complete at least one of the criteria search boxes for Job Title, Vacancy Type or Country.</span></li>";
            //SetObjBgColour("LocationTxtbox", "#ffff00");
            SetObjBgColour("txtJobTitleJobAlert", "#ffff00");
            SetObjBgColour("ddlCountryJobAlert", "#ffff00");
            SetObjBgColour("ddlVacancyTypeJobAlert", "#ffff00");
        }
        else if (emailChecked == false && textMsgChecked == false) {
            notificationValidationMsg = "<li><b>You have not ticked whether you wish to receive Notifications by email and/or text message!</b><br /><br />Please tick your required notification types.</li>";
        }
        else  // continue with specific combination validation
        {
            if (jobMatchNotificationName == "") {
                notificationValidationMsg = "<li><b>Please enter a Job Alert Title!</b></li>";
                SetObjBgColour("txtJobMatchNotificationName", FailedValBg);
            }

            if (emailChecked == true && email == "") {
                notificationValidationMsg = "<li><b>You have ticked to receive notifications by email but have not entered an email address!</b><br /><br />Please enter an email address or un-tick the 'Email Job Match Notifications' tickbox.</li>";
                SetObjBgColour("txtJobNotificationEmail", FailedValBg);
            }

            if (textMsgChecked == true && mobileNum == "") {
                notificationValidationMsg += "<li><b>You have ticked to receive notifications by Text Message but have not entered a Mobile Number!</b><br /><br />Please enter a Mobile Number or un-tick the 'Send Text Message Job Match Notifications' tickbox.</li>";
                SetObjBgColour("txtJobNotificationMobileNumber", FailedValBg);
            }

            if (IsValidEMailAddressFormat(email) == false && email != "") {
                notificationValidationMsg += "<li><b>The Email address you entered is not in a valid format!</b> <br /><br />Please ensure there are no spaces, period or commas in the address!<br /><br />Please correct the email address or un-tick the 'Email Job Match Notifications' tickbox.</li>";
                SetObjBgColour("txtJobNotificationEmail", FailedValBg);
            }

            // check correctly entered mobile number i.e. no + prefix no 00 prefix
            if (mobileNum.Trim() != "" && textMsgChecked == true && validateMobileNumber(mobileNum) == false) {
                notificationValidationMsg += "<li><b>The Mobile Number you entered is not in the required format - please correct!<br /><br />Please enter numbers only. Do not include country code or + sign.</b></li>";
                SetObjBgColour("txtJobNotificationMobileNumber", FailedValBg);
            }
        }

        if (notificationValidationMsg == "")  // successful validation
        {
            ShowHideAnimatedMsgBox("visible", "Saving Job Match Notification");
            PageMethods.AddJobMatchNotification(countryId, email, jobTitle, "", mobileCountryCodePrefix, mobileNum, emailChecked, textMsgChecked, vacancyTypeId, jobMatchNotificationName, AddNotificationRequestComleted, UpdateRequestError);
        }
        else   // validation faled
        {
            var errMsg = "<ul class='errorUl'>" + notificationValidationMsg + "</ul>";
            ShowModalMsgBox(errMsg);
        }
    }
}



function AddNotificationRequestComleted(responseMsg) {
    ShowHideAnimatedMsgBox("hidden", "");

    if (responseMsg.indexOf("Successfully Added") != -1) {
        // CloseJobNotificationPopup();
        responseMsg += "<br /><br />You can Remove or edit your saved Job Match Notifications via the 'Job Match Notification' tab in your User Account area.";
        document.getElementById("txtJobMatchNotificationName").value = "";
    }

    //ShowModalMsgBox("<p>" + responseMsg + "</p>");
    document.getElementById("SaveJobMatchResponseMessage").innerHTML = responseMsg;
    DisplayHideObj("SaveJobMatchResponseMessage", "block");

}


function validateMobileNumber(mobNum) {
    // remove spaces and then validate if a number entered
    var mobNumberNoSpaces = mobNum.replace(/\s+/g, "");
    // validate only numbers/digits entered (doesn't matter if they have included spaces in number as we will strip out spaces before adding to database)
    var isValidMobNum = true;
    var regExpStr = "^[0-9]+$";  // believe mobile numbers contain 10 to 11 (soon) digits but used 9 to 12 as range just in case
    var regexMobNum = new RegExp(regExpStr);
    isValidMobNum = regexMobNum.test(mobNumberNoSpaces);

    return isValidMobNum;
}


function NotificationCheckboxOnBlur(checkboxId) {
    // if checkbox checked = false then clear it's associated input box
    if (document.getElementById(checkboxId).checked == false) {
        if (checkboxId == "chkEmail") {
            document.getElementById("txtJobNotificationEmail").value = "";
        }
        else if (checkboxId == "chkTextMessage") {
            document.getElementById("txtJobNotificationMobileNumber").value = "";
        }
    }
}