﻿// Default product search field text
var PRODUCT_SEARCH_FIELD_DEFAULT="Enter product or service";
// Default company search field text
var COMPANY_SEARCH_FIELD_DEFAULT="Enter company name";
// The minimum number of chars typed before the suggestion box appears
var MIN_CHARS_FOR_FIELD_SUGGESTION=2;
// The minimum number of companies required to do a comparison
var MIN_COMPANIES_FOR_COMPARISON=2;
// The maximum number of companies allowed to do a comparison
var MAX_COMPANIES_FOR_COMPARISON=4;


// An array for maintaining a list of the companies selected for comparison
var CompaniesToCompare=new Array();


// Things to do after the search page loads
function InitSearchPage(){
    // Set the search fields to their initial state
    document.getElementById("ProductSearchField").value=PRODUCT_SEARCH_FIELD_DEFAULT;
    document.getElementById("CompanySearchField").value=COMPANY_SEARCH_FIELD_DEFAULT;
}


// Things to do after the search results page loads
function InitSearchResultsPage(){
    // Show the category results for product/true search
    DisplayProductSearchResults(0);
    // Show the company search results
    DisplayCompanyResultsPage(-1);
}


// See if the given Value is in the given Array and return true/false based on that
function InArray(ValArray, Value){
    var LoopVar;
    for (LoopVar=0; LoopVar<ValArray.length; LoopVar++){
        if (ValArray[LoopVar]==Value){
            return true;
        }
    }
    return false;
}


// Get and display the search suggestions
// Pass either 'Products' or 'Companies' as text to SearchType to differentiate the suggestions
function GetSearchSuggestions(SearchType, SearchTerm){
    // See if the search term is of acceptable length
    if (SearchTerm.length>=MIN_CHARS_FOR_FIELD_SUGGESTION){
        if (SearchType=="Products"){
            PopulateElement("ProductSuggestionsLabel", "ajax/getsearchsuggestions.aspx?Filter="+escape(SearchTerm)+"&SearchType="+escape(SearchType), "&nbsp;")
            ShowElement("ProductSuggestionsArea", true);
         } else if (SearchType=="Companies"){
            PopulateElement("CompanySuggestionsLabel", "ajax/getsearchsuggestions.aspx?Filter="+escape(SearchTerm)+"&SearchType="+escape(SearchType), "&nbsp;")
            ShowElement("CompanySuggestionsArea", true);
        }
    // The search term is not of acceptable length, hide the suggestion boxes
    } else {
        if (SearchType=="Products"){
            ShowElement("ProductSuggestionsArea", false);
            document.getElementById("ProductSuggestionsLabel").innerHTML="";
         } else if (SearchType=="Companies"){
            ShowElement("CompanySuggestionsArea", false);
            document.getElementById("CompanySuggestionsLabel").innerHTML="";
        }
    }
    return false;
}


// Sets the search field to the passed SearchTerm and hides the suggestion box
// Pass either 'Products' or 'Companies' as text to SearchType to differentiate the fields
function SetSearchTerm(SearchType, SearchTerm){
    if (SearchType=="Products"){
        document.getElementById("ProductSearchField").value=SearchTerm;
        document.getElementById("ProductSearchField").focus();
        ShowElement("ProductSuggestionsArea", false);
    } else if (SearchType=="Companies"){
        document.getElementById("CompanySearchField").value=SearchTerm;
        document.getElementById("CompanySearchField").focus();
        ShowElement("CompanySuggestionsArea", false);
    }
    return false;
}


// Perform any tasks that should happen when entering the search field
// Pass either 'Products' or 'Companies' as text to SearchType to differentiate the fields
function EnteringSearchField(SearchType, SearchField){
    if (SearchType=="Products"){
        if (SearchField.value==PRODUCT_SEARCH_FIELD_DEFAULT){
            SearchField.value="";
        }
    } else if (SearchType=="Companies"){
        if (SearchField.value==COMPANY_SEARCH_FIELD_DEFAULT){
            SearchField.value="";
        }
    }
    SearchField.className="SearchFieldActiveStyle";
    SearchField.select();
    GetSearchSuggestions(SearchType, SearchField.value);
}


// Perform any tasks that should happen when leaving the search field
// Pass either 'Products' or 'Companies' as text to SearchType to differentiate the fields
function LeavingSearchField(SearchType){
    if (SearchType=="Products"){
        ShowElement("ProductSuggestionsArea", false);
    } else if (SearchType=="Companies"){
        ShowElement("CompanySuggestionsArea", false);
    }
}


// Perform any tasks that should happen when entering the search suggestion area
function EnteringSearchSuggestionArea(SearchArea){
    ShowElement(SearchArea.id, true);
}


// Perform any tasks that should happen when leaving the search suggestion area
function LeavingSearchSuggestionArea(SearchField){
    document.getElementById(SearchField).focus();
}


// Initiate the call to get the product line contents and display in the appropriate area
function GetProductLineContents(ProductLineID){
    var LoopVar=0;
    if (document.getElementById("ProductLineContents"+ProductLineID).style.visibility=="visible"){
        ShowElement("ProductLineContents"+ProductLineID, false);
        document.getElementById("ProductLineContents"+ProductLineID).innerHTML="";
    } else {
        // Hide other product line areas when this one is showing
        var OptionsIn=document.getElementsByTagName("div");
        for (LoopVar=0; LoopVar<OptionsIn.length; LoopVar++){
            if (OptionsIn[LoopVar].getAttribute("name")=="ProductLineContentsArea"){
                OptionsIn[LoopVar].style.position="absolute";
                ShowElement(OptionsIn[LoopVar].id, false);
                OptionsIn[LoopVar].innerHTML="";
            }
        }
        // Display the current product line contents
        document.getElementById("ProductLineContents"+ProductLineID).style.position="relative";
        PopulateElement("ProductLineContents"+ProductLineID, "ajax/getproductlinecontents.aspx?ProductLineID="+ProductLineID);
        ShowElement("ProductLineContents"+ProductLineID, true);
    }
}


// Launch the category page for the given CatID
function GoToCategoryPage(CatID){
    window.location="search.aspx?CatID="+escape(CatID);
    return false;
}


// Launch the company page for the given CompanyID
function GoToCompanyPage(CompanyID){
    window.location="search.aspx?CompanyID="+escape(CompanyID);
    return false;
}


// A company comparison checkbox was changed; add it or remove it from the list
function CompanyComparisonBoxChanged(ComparisonCheckbox){
    var NewCompaniesToCompare=new Array();
    var LoopVar;
    for (LoopVar=0; LoopVar<CompaniesToCompare.length; LoopVar++){
        if (CompaniesToCompare[LoopVar]!=ComparisonCheckbox.value){
            NewCompaniesToCompare.push(CompaniesToCompare[LoopVar]);
        }
    }
    if (ComparisonCheckbox.checked && !InArray(CompaniesToCompare, ComparisonCheckbox.value)){
        NewCompaniesToCompare.push(ComparisonCheckbox.value);
    }
    CompaniesToCompare=NewCompaniesToCompare;
    CheckComparisonBoxes('CompanySearchCompareButton', 'CompaniesToCompare');
}


// Check to see if the right number of checkboxes for company comparison are checked or if too many are checked
// Pass the ID of the comparison button and the NAME of the checkboxes
function CheckComparisonBoxes(ComparisonButton, ComparisonCheckboxes){
    var OptionsIn=document.getElementsByName(ComparisonCheckboxes);
    var CompanyCount=CompaniesToCompare.length;
    var DefaultStateForBoxes=!(CompanyCount<MAX_COMPANIES_FOR_COMPARISON);

    // Set the operability of the comparison button
    if (UserLoggedIn){
        document.getElementById(ComparisonButton).disabled=(CompanyCount<MIN_COMPANIES_FOR_COMPARISON || (CompanyCount>MAX_COMPANIES_FOR_COMPARISON));
    } else {
        document.getElementById(ComparisonButton).disabled=true;
    }

    // Loop through all of the company comparison checkboxes on the page to set their state and operability
    var LoopVar;
    for (LoopVar=0; LoopVar<OptionsIn.length; LoopVar++){
        if (UserLoggedIn){
            if (InArray(CompaniesToCompare, OptionsIn[LoopVar].value)){
                OptionsIn[LoopVar].checked=true;
                OptionsIn[LoopVar].disabled=false;
            } else {
                OptionsIn[LoopVar].checked=false;
                OptionsIn[LoopVar].disabled=DefaultStateForBoxes;
            }
        } else {
            OptionsIn[LoopVar].disabled=true;
        }
    }
}


// Launch the company comparison page given the options selected in the checkbox array with the given name (ComparisonCheckboxes)
// The value of the checkboxes is the <Company ID>|<Div ID>
function GoToComparisonPage(){
    if (UserLoggedIn){
        var QueryToPass="";
        var CompanyCount=CompaniesToCompare.length;
        var LoopVar;
        for (LoopVar=0; LoopVar<CompanyCount; LoopVar++){
            QueryToPass+="&Company"+(LoopVar+1)+"="+escape(CompaniesToCompare[LoopVar]);
        }
        if (CompanyCount<MIN_COMPANIES_FOR_COMPARISON){
            alert('Please select at least '+MIN_COMPANIES_FOR_COMPARISON+' compan'+(MIN_COMPANIES_FOR_COMPARISON==1?'y':'ies')+' to compare by using the checkboxes next to the company names.');
            return false;
        }
        if (CompanyCount>MAX_COMPANIES_FOR_COMPARISON){
            alert('Please select no more than '+MAX_COMPANIES_FOR_COMPARISON+' compan'+(MAX_COMPANIES_FOR_COMPARISON==1?'y':'ies')+' to compare.');
            return false;
        }
        QueryToPass="?CompanyCount="+CompanyCount+QueryToPass;
        window.open("search.aspx"+QueryToPass);
    } else {
        alert("You must sign in or register to use this feature.");
    }
    
    return false;
}


// Reset all company filters to their initial state
function ResetCompanyFiltersAll(){
    // Activity Type Filters
    ResetCompanyFilters("ActivityTypeFilters");

    // State Filters
    ResetCompanyFilters("StateFilters");

    // Location Filters
    ResetCompanyFilters("LocationFilters");
    ResetCompanyFilters("LocationFilters2");

    // Number of Employees Filters
    ResetCompanyFilters("NumberEmployeesFilters");

    // Facility Area Filters
    ResetCompanyFilters("FacilityAreaFilters");

    // Ownership Type Filters
    ResetCompanyFilters("OwnershipTypeFilters");

    DisplayCompanyResultsPage(-2);
}


// Reset the filters with the given name to their initial state
function ResetCompanyFilters(CBName){
    var OptionsIn=document.getElementsByName(CBName);
    var LoopVar;
    for (LoopVar=0; LoopVar<OptionsIn.length; LoopVar++){
        OptionsIn[LoopVar].checked=false;
    }
    DisplayCompanyResultsPage(-2);
}


// Apply the given filter to the company results
function ApplyCompanyFilters(TheCB){
    DisplayCompanyResultsPage(-2);
    CheckCompanyFilterForAllChecked(TheCB.getAttribute("name"));
}


// Keep the 'All' checkbox in synch with the current filter set
function CheckCompanyFilterForAllChecked(FilterSetName){
    // See if all checkboxes in the set are checked and keep the 'All' box in synch
    var AllChecked=true;
    var OptionsIn=document.getElementsByName(FilterSetName);
    var LoopVar;
    var AllCB=null;
    for (LoopVar=0; LoopVar<OptionsIn.length; LoopVar++){
        if (OptionsIn[LoopVar].value==""){
            AllCB=OptionsIn[LoopVar];
        } else if (!OptionsIn[LoopVar].checked){
            AllChecked=false;
        }
    }
    if (AllCB!=null){
        AllCB.checked=AllChecked;
    }
}


// Apply the given filter to all of the checkboxes matching the current one's name
function ApplyCompanyFilterAll(AllCB){
    var OptionsIn=document.getElementsByName(AllCB.getAttribute('name'));
    var LoopVar;
    for (LoopVar=0; LoopVar<OptionsIn.length; LoopVar++){
        OptionsIn[LoopVar].checked=AllCB.checked;
    }
    // Handle associated states if selecting 'LocationFilters'
    if (AllCB.getAttribute('name')=="LocationFilters"){
        OptionsIn=document.getElementsByName(AllCB.getAttribute('name')+"2");
        for (LoopVar=0; LoopVar<OptionsIn.length; LoopVar++){
            OptionsIn[LoopVar].checked=AllCB.checked;
        }
    }
    DisplayCompanyResultsPage(-2);
}


// Show/Hide a particular filter set
function ShowFilterSet(SetID){
    if (document.getElementById(SetID).className=="FilterSetStyle"){
        document.getElementById(SetID+"ExpansionIndicator").src="/Directory/images/arrow_down.gif";
        document.getElementById(SetID).className="FilterSetStyleOpen";
    } else {
        document.getElementById(SetID+"ExpansionIndicator").src="/Directory/images/arrow_right.gif";
        document.getElementById(SetID).className="FilterSetStyle";
    }
}


// Handle the key down event for the search fields by trapping the 'enter' key and forwarding to the right search
function SearchFieldKeyDown(SearchType, Event){
    if (Event.keyCode==13){
        SubmitSearchTerm(SearchType);
        return false;
    }
    return true;
}


// Submit one of the search fields
function SubmitSearchTerm(SearchType){
    var QueryToPass="";
    if (SearchType=="Products"){
        QueryToPass="?ProductSearchTerm="+escape(document.getElementById('ProductSearchField').value);
    } else if (SearchType=="Companies"){
        QueryToPass="?CompanySearchTerm="+escape(document.getElementById('CompanySearchField').value);
    }
    window.location="search.aspx"+QueryToPass;
    return false;
}


// Return the query string snippet associated with the given filter set
// If DiscardIfAll is either passed true or not passed, don't send filters which are all checked
function GetCurrFiltersCheckedQuery(CurrFilterSet, DiscardIfAll){
    // Default DiscardIfAll to true
    if (DiscardIfAll==null){
        DiscardIfAll=true;
    }

    var TxtOut="";
    var CurrFilters;
    var LoopVar;
    var AllChecked=true;

    // Get filter checkboxes
    var OptionsIn=document.getElementsByName(CurrFilterSet);
    CurrFilters=new Array();

    // Add all checked filter options to an array only if it also has a value
    for (LoopVar=0; LoopVar<OptionsIn.length; LoopVar++){
        if (OptionsIn[LoopVar].value!=""){
            if (OptionsIn[LoopVar].checked){
                CurrFilters.push(OptionsIn[LoopVar].value);
            } else {
                AllChecked=false;
            }
        }
    }
    
    // Handle additional states for 'LocationFitlers'
    if (CurrFilterSet=="LocationFilters"){
        OptionsIn=document.getElementsByName(CurrFilterSet+"2");
        for (LoopVar=0; LoopVar<OptionsIn.length; LoopVar++){
            if (OptionsIn[LoopVar].value!=""){
                if (OptionsIn[LoopVar].checked){
                    CurrFilters.push(OptionsIn[LoopVar].value);
                } else {
                    AllChecked=false;
                }
            }
        }
    }
    
    // Take the array of checked filter options and generate a query string snippet for it
    if (CurrFilters.length>0 && !(AllChecked && DiscardIfAll)){
        TxtOut+="&"+CurrFilterSet+"=";
        for (LoopVar=0; LoopVar<CurrFilters.length; LoopVar++){
            TxtOut+=(LoopVar>0?"|":"")+escape(CurrFilters[LoopVar]);
        }
    }
    
    return TxtOut;
}


// Return the query string given all of the company filter checkboxes
function GetAllFiltersQuery(){
    var TxtOut="";

    // Activity Type Filters
    TxtOut+=GetCurrFiltersCheckedQuery("ActivityTypeFilters");

    // Location Filters
    TxtOut+=GetCurrFiltersCheckedQuery("LocationFilters", false);

    // Number of Employees Filters
    TxtOut+=GetCurrFiltersCheckedQuery("NumberEmployeesFilters");

    // Facility Area Filters
    TxtOut+=GetCurrFiltersCheckedQuery("FacilityAreaFilters");

    // Ownership Type Filters
    TxtOut+=GetCurrFiltersCheckedQuery("OwnershipTypeFilters");

    return TxtOut;
}


// Show the product search results
// Pass the number of results to display (0 is the default, -1 is all)
function DisplayProductSearchResults(NumResults){
    if (document.getElementById("ProductSearchResultsLabel")!=null){
        if (NumResults==null){
            NumResults=0;
        }
        var QueryToPass=document.location.search;
        QueryToPass+=GetAllFiltersQuery();
        QueryToPass+="&ProductSearchResultsToShow="+parseInt(NumResults)
        PopulateElement("ProductSearchResultsLabel", "ajax/getproductsearchresults.aspx"+QueryToPass);
    }
}


// Switch to the given page of company search results
// Pass 1 for page 1
// Pass 0 for all results
// Pass -1 for default/last results
// Pass -2 for automatic first page (0 or 1 based on the last search)
function DisplayCompanyResultsPage(PageNum, ScrollTop){
    if (ScrollTop==null){
        ScrollTop=false;
    }

	if(navigator.userAgent=="dtSearchSpider"){PageNum=0;}

    var QueryToPass=document.location.search;
    QueryToPass+=GetAllFiltersQuery();
    QueryToPass+="&PageNum="+parseInt(PageNum)

    PopulateElement("CompanySearchResultsLabel", "ajax/getcompanysearchresults.aspx"+QueryToPass, null, "CheckComparisonBoxes(\"CompanySearchCompareButton\", \"CompaniesToCompare\");"+(PageNum==-1?" DisplayCompanySearchFilters();":""));

    // Jump back to the top of the page (in case page links are clicked from the bottom of the page)
    if (ScrollTop){
        window.scroll(0, 0);
    }
}


// Display the company search filters
function DisplayCompanySearchFilters(){
    var QueryToPass=document.location.search;
    var CodeToFollow="";
    CodeToFollow=CodeToFollow+"CheckCompanyFilterForAllChecked(\"ActivityTypeFilters\");";
    CodeToFollow=CodeToFollow+"CheckCompanyFilterForAllChecked(\"LocationFilters\");";
    CodeToFollow=CodeToFollow+"CheckCompanyFilterForAllChecked(\"NumberEmployeesFilters\");";
    CodeToFollow=CodeToFollow+"CheckCompanyFilterForAllChecked(\"FacilityAreaFilters\");";
    CodeToFollow=CodeToFollow+"CheckCompanyFilterForAllChecked(\"OwnershipTypeFilters\");";
    PopulateElement("CompanySearchFilterLabel", "ajax/getcompanysearchfilters.aspx"+QueryToPass, null, CodeToFollow);
}