﻿// 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
	var Element=document.getElementById("BGHeader_ProductSearchField");
	if (Element){
		if (Element.value==""){
			Element.value=PRODUCT_SEARCH_FIELD_DEFAULT;
		}
	}
	var Element=document.getElementById("BGHeader_CompanySearchField");
	if (Element){
		if (Element.value==""){
			Element.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);
}


// Things to do after the category page loads
function InitCategoryPage(){
	DisplayCompanySearchFilters();
}


// 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("BGHeader_ProductSuggestionsLabel", "/ajax/getsearchsuggestions.aspx?Filter="+escape(SearchTerm)+"&SearchType="+escape(SearchType), "&nbsp;")
			ShowElement("BGHeader_ProductSuggestionsArea", true);
		 } else if (SearchType=="Companies"){
			PopulateElement("BGHeader_CompanySuggestionsLabel", "/ajax/getsearchsuggestions.aspx?Filter="+escape(SearchTerm)+"&SearchType="+escape(SearchType), "&nbsp;")
			ShowElement("BGHeader_CompanySuggestionsArea", true);
		}
	// The search term is not of acceptable length, hide the suggestion boxes
	} else {
		if (SearchType=="Products"){
			ShowElement("BGHeader_ProductSuggestionsArea", false);
			document.getElementById("BGHeader_ProductSuggestionsLabel").innerHTML="";
		 } else if (SearchType=="Companies"){
			ShowElement("BGHeader_CompanySuggestionsArea", false);
			document.getElementById("BGHeader_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("BGHeader_ProductSearchField").value=SearchTerm;
		document.getElementById("BGHeader_ProductSearchField").focus();
		ShowElement("BGHeader_ProductSuggestionsArea", false);
	} else if (SearchType=="Companies"){
		document.getElementById("BGHeader_CompanySearchField").value=SearchTerm;
		document.getElementById("BGHeader_CompanySearchField").focus();
		ShowElement("BGHeader_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("BGHeader_ProductSuggestionsArea", false);
	} else if (SearchType=="Companies"){
		ShowElement("BGHeader_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="Category.aspx?CatID="+escape(CatID);
	return false;
}


// Launch the company page for the given CompanyID
function GoToCompanyPage(CompanyID){
	window.location="Company.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("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(ComparisonCheckboxes){
	var OptionsIn=document.getElementsByName(ComparisonCheckboxes);
	var CompanyCount=CompaniesToCompare.length;
	var DefaultStateForBoxes=!(CompanyCount<MAX_COMPANIES_FOR_COMPARISON);

	// 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("CompanyComparison.aspx"+QueryToPass);
	} else {
		alert("Please 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="/images/directory/arrow_down.gif";
		document.getElementById(SetID).className="FilterSetStyleOpen";
	} else {
		document.getElementById(SetID+"ExpansionIndicator").src="/images/directory/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('BGHeader_ProductSearchField').value);
	} else if (SearchType=="Companies"){
		QueryToPass="?CompanySearchTerm="+escape(document.getElementById('BGHeader_CompanySearchField').value);
	}
	window.location="/SearchResults.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)

	if (PageNum==-1){
		CheckComparisonBoxes("CompaniesToCompare");
		DisplayCompanySearchFilters();
	} else {
		if (document.getElementById("FeaturedCompanySearchResultsLabel")){
			PopulateElement("FeaturedCompanySearchResultsLabel", "/ajax/getcompanysearchresults.aspx"+QueryToPass+"&AdvertisersOnly=1", "<center><img src=\"/images/directory/loading.gif\" width=\"169\" height=\"39\" alt=\"\" /></center>", "CheckComparisonBoxes(\"CompaniesToCompare\");"+(PageNum==-1?" DisplayCompanySearchFilters();":""));
		}
		PopulateElement("CompanySearchResultsLabel", "/ajax/getcompanysearchresults.aspx"+QueryToPass, "<center><img src=\"/images/directory/loading.gif\" width=\"169\" height=\"39\" alt=\"\" /></center>", "CheckComparisonBoxes(\"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);
}


// Show/hide the filter box
function ToggleFilterBox(){
	if (UserLoggedIn){
		var Box=document.getElementById("CompanySearchFilterArea");
		if (Box){
			var Btn=document.getElementById("FilterBoxButton");
			if (Box.style.display!="block"){
				Box.style.display="block";
				if (Btn){
					Btn.src="/images/Directory/filter_button_down.png";
				}
			} else {
				Box.style.display="none";
				if (Btn){
					Btn.src="/images/Directory/filter_button_up.png";
				}
			}
		}
	} else {
		alert("Please sign in or register to use this feature.\nFilters allow you to find companies based on location, size, type, etc...");
	}
}



// Scroll to the previous/next company print ad.  Assumes "CompanyPrintAds" was pre-defined.
var CurrentCompanyPrintAd=0;
var CompanyPrintAdCellWidth=235;
function ScrollCompanyPrintAds(Step){
	if (!CompanyPrintAds){
		CompanyPrintAds=1;
	}
	while(Step<0){
		Step+=CompanyPrintAds;
	}
	CurrentCompanyPrintAd=(CurrentCompanyPrintAd+Step)%CompanyPrintAds;
	ScrollPrintAdsTo(CurrentCompanyPrintAd*CompanyPrintAdCellWidth);
}


// Company print ads scroller
var CompanyPrintAdScrollTimer=null;
function ScrollPrintAdsTo(XPos, RemainingSteps){
	if (RemainingSteps==null){
		if (CompanyPrintAdScrollTimer){
			clearTimeout(CompanyPrintAdScrollTimer);
		}
		RemainingSteps=15;
	}
	var Element=document.getElementById("CompanyPrintAdScroller");
	if (Element){
		Element.scrollLeft=(Element.scrollLeft+XPos)/2;
	}
	if (RemainingSteps>0){
		CompanyPrintAdScrollTimer=setTimeout("ScrollPrintAdsTo("+XPos+", "+(RemainingSteps-1)+");", 40);
	} else {
		Element.scrollLeft=XPos;
	}
}



// Scroll to the previous/next category product
var CategoryProductCellWidth=150;
function ScrollCategoryProducts(Step){
	var Element=document.getElementById("CategoryProductsBox");
	if (Element){
		var DestX=((Math.floor(Element.scrollLeft/CategoryProductCellWidth)*CategoryProductCellWidth)+(Step*CategoryProductCellWidth));
		if(DestX>Element.scrollWidth-Element.offsetWidth){
			DestX=0;
		}
		if(DestX<0){
			DestX=Element.scrollWidth-Element.offsetWidth;
		}
		ScrollCategoryProductsTo(DestX);
	}
}


// Category products scroller
var CategoryProductsScrollTimer=null;
function ScrollCategoryProductsTo(XPos, RemainingSteps){
	if (RemainingSteps==null){
		if (CategoryProductsScrollTimer){
			clearTimeout(CategoryProductsScrollTimer);
		}
		RemainingSteps=15;
	}
	var Element=document.getElementById("CategoryProductsBox");
	if (Element){
		Element.scrollLeft=(Element.scrollLeft+XPos)/2;
	}
	if (RemainingSteps>0){
		CategoryProductsScrollTimer=setTimeout("ScrollCategoryProductsTo("+XPos+", "+(RemainingSteps-1)+");", 40);
	} else {
		Element.scrollLeft=XPos;
	}
}


// Launch the given URL
function listings(site) {
	if (site) {
		self.location=site;
	}
}

