﻿// 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'></div><h6>Location Tip</h6><p>Enter City/Town name here. If you are looking for Oil industry Offshore work, then type Offshore here.</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'></div><h6>Job Title Tip</h6><p>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'></div><h6>Job Description Keywords Tip</h6><p>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>";
    
//    var LocationHelpTip = "<p><b>Location Keywords Tip:</b><br />Enter city/town name here. If you are looking for Oil industry Offshore work, then type Offshore here.</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><b>Note: </b> Do not enter quotes around location names. Do not use ' AND ' / ' OR ' keyword logic between location keywords (simply seperate your keywords using a comma).</p>";
//    var JobTitleHelpTip = "<p><b>Job Title Keywords Tip:</b><br />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><b>Note: </b> Do not enter quotes around Job Titles. Do not use ' AND ' / ' OR ' keyword logic between Job Title keywords (simply seperate your keywords using a comma).</p>";
//    var KeywordsHelpTip = "<p><b>Job Description Keywords Tip:</b><br />Enter any keywords you wish to find in the Job Description e.g. skills keywords, qualification keywords, role or responsibility keywords etc e.g. technical lead, team lead. Our system will return any vacancies that contain 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.</p><p>Use the Job Description Keyword tickboxes under this box to specify if the Job Description should contain Any or All of your keywords.</p><p><b>Note: </b> Do not enter quotes around Job Description keywords. Do not use ' AND ' / ' OR ' keyword logic between Job Description keywords (simply seperate your keywords using a comma).</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()
    {
        document.getElementById("IndustryListValMsg").style.display = "none";  // ensure validation msg hidden
        document.getElementById("IndustryList").style.backgroundColor = "#ffffff";
        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 industryListValue = GetControlValue("IndustryList");          //   GetListSelectedValues("IndustryList");
        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(industryListValue == "0")
        {
            industryListValue = "";
        }
        
        if( countryListSelectedValue == "0" )
        {
            countryListSelectedValue = "";
        }
        
       // 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(industryListValue, 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)
    {
        CurrentJobDetailId = jobDetailsDivId;
        JobId = id;
        CurrentlyViewingJobTitle = jobTitle;
        document.title = "IFA 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);

    //alert("pop h = " + JobPopH + " scroll h = " + scrollH);
        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");
        
        // show job detail popup div
        ShowHideObj("ViewJobPopup","visible");
    }
    
    
   
   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"); // function defined in universal.js
		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)
    {
       document.getElementById("AjaxUpdateMessageBar").innerHTML = "Sending Job Application ...";
       SetObjectOpacity("AjaxUpdateMessageBar",100);
       ShowHideObj("AjaxUpdateMessageBar","visible");
      // PageMethods.ApplyForVacancy(JobId,JobApplicationRequestCompleted,UpdateRequestError,JobId);
      
      var clientRef = GetControlValue("txtClientRef" + JobId);
      var forwardTo = GetControlValue("txtForwardApplicationToEmail" + JobId);
      //alert("clientRef = " + clientRef + "\n\n forward to = " + forwardTo);
      PageMethods.ApplyForVacancy(JobId,clientRef,forwardTo,JobApplicationRequestCompleted,UpdateRequestError,JobId);
    }
    else
    {
       ShowHideOkMsgBox("visible",'You must <a href="#" onclick="RedirectToLogin();return false;">Login</a> / <a href="https://ifa-voice.com/Register.aspx">Register</a> to use this feature!');
    }
 }
 
 
 function JobApplicationRequestCompleted(responseHtml, context)
 {
    if( responseHtml.indexOf("Job Application Not Sent") != -1 || responseHtml.indexOf("Job Application Failed") != -1 )
    {
        autoCloseAjaxMsgBar();
        ShowHideOkMsgBox("visible",responseHtml);
    }
    else
    {
        SetObjectOpacity("AjaxUpdateMessageBar",100);
        ShowHideObj("AjaxUpdateMessageBar","visible");
        document.getElementById("AjaxUpdateMessageBar").innerHTML = responseHtml;
        setTimeout("autoCloseAjaxMsgBar()",4000);
        // ?? SendingApplication = false;
        AppliedForJobsArray.push(context);
    }
 }
 
 // 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);
 }

 
//  ============================== STORE JOB ========================================
 
  function StoreJob()
 {
    if(LoggedInUser == true)
    {
       // alert("fire ajax request!  store job id = " + JobId);
       document.getElementById("AjaxUpdateMessageBar").innerHTML = "Storing Job ...";
       SetObjectOpacity("AjaxUpdateMessageBar",100);
       ShowHideObj("AjaxUpdateMessageBar","visible");
       PageMethods.StoreJob(JobId,StoreJobRequestCompleted,DataRequestError,JobId);
    }
    else
    {
       ShowHideOkMsgBox("visible",'You must <a href="#" onclick="RedirectToLogin();return false;">Login</a> / <a href="https://ifa-voice.com/Register.aspx">Register</a> to use this feature!');
    }
 }
 
 
 function StoreJobRequestCompleted(responseHtml, context)
 {
    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);
    }
 }
 


// ====================== 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 cookieString = industryListValue + "^" + countryListSelectedValues + "^" + location + "^" + vacancyTypeListValue + "^" + jobtitle + "^" + keywords + "^" + boolAnyKeywords + "^" + boolAllKeywords + "^" + postedWithin + "^" + sortBy;
        
        //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="IndustryList" type="list">' + industryListValue + '</item><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="https://ifa-voice.com/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);
    
    if(response.indexOf('Job Search Criteria Saved') != -1)
    {
        SetObjectOpacity("AjaxUpdateMessageBar",100);
        ShowHideObj("AjaxUpdateMessageBar","visible");
        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 Report 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; }
                  }
                  
                }  // end for loop
                
               
                
                // TESTING output write
                //document.getElementById("debugarea").value = testMsg;
                          

            }  // end restore else block
    }
   
   
   // =================================== DISABLE SEARCH ELEMENTS  ===============================
   
     var SearchElementsArray = new Array("SaveSearchBtn","IndustryList","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 = "#66cc33";
  
  function ShowFocusHelpTip(tiptext,tipwidth,xpos,ypos,controlid)
  {
    document.getElementById(controlid).style.backgroundColor = FocusHelpTipBg;
    FocusTip(tiptext,tipwidth,xpos,ypos);
  }
  
  function HideFocusHelpTip(controlid)
  {
    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()
{
//    var redirect = "Login.aspx";
//    if(JobId != 0) { redirect = "Login.aspx?jobid=" + JobId; }
    top.location.href = "https://ifa-voice.com/Login.aspx?jobid=" + JobId;
}

//function FadeOut(objid)
//{
// var el = $get("sendToFriendWrapper");
//    AjaxControlToolkit.Animation.OpacityAction.play(el, 0, 30, 0);
//    
////    var obj = $get("sendToFriendWrapper");                            //This is a shortcut for document.getElementById. It will return the javascript element. This is the element that you want to fade.
////    var target = new Sys.UI.Control(obj);               //The animation does not need a javascript element. It wants a Control. So use the element to instantiate the control.
////    var animation = new Sys.UI.FadeAnimation();         //Instantiate
////    animation.set_target(target);                       //An animation has to have a target to act upon.
////    animation.set_effect(Sys.UI.FadeEffect.FadeOut);    //This determines whether a fade out or fade in is going to be executed.
////    animation.set_duration(2);                          //How long the animation will last.
////    animation.set_fps(25);                              //How many frames per second the animation should execute.
////    animation.play();                                   //Once everything is setup, it can be executed.
//}


//function fadetest()
//{
//  var el = $get("sendToFriendWrapper");
//    AjaxControlToolkit.Animation.OpacityAction.play(el, 0, 30, 0.4);
//}



