addLoadEvent(function () {
	BuyersGuide.init();
});

var BuyersGuide = (function () {

	// HTML elements to be used throughout function
	var categorySelectEl;
	var subcategorySelectEl;
	var subcategoryLiEl;
	var searchResultsEl;
	var searchResultsGoldEl;
	var searchResultsSilverEl;
	var searchResultsBronzeEl;
	var selectedCategoryId;
	var selectedSubcategoryId;
	var noSearchResultsMessage;

	// Preload AJAX loading icon image
	var ajaxLoadingIconEl = document.createElement('img');
	ajaxLoadingIconEl.setAttribute('src',	'../images/icons/loading.gif');
	ajaxLoadingIconEl.setAttribute('id',	'buyersGuide_ajaxLoadingIcon');

	// Default HTML of <select>s
	var defaultSelectInnerHtml = '<option value="0">- Select -</option>';

	return {

		init : function () {

			// Grab elements from DOM which are used throughout class
			categorySelectEl				= $('selectCategory');
			subcategorySelectEl			= $('selectSubcategory');
			subcategoryLiEl					= $('liSubcategory');
			searchResultsEl					= $('buyersGuide_searchResults');
			searchResultsGoldEl			= $('buyersGuide_searchResultsGold');
			searchResultsSilverEl		= $('buyersGuide_searchResultsSilver');
			searchResultsBronzeEl		= $('buyersGuide_searchResultsBronze');
			noSearchResultsMessage	= $('buyersGuide_noSearchResults');

			if (!categorySelectEl) return false;
			
			// Hide the AJAX loading icon and insert it into the DOM to be shown when appropriate
			ajaxLoadingIconEl.style.display = 'none';
			searchResultsEl.appendChild(ajaxLoadingIconEl);

			// Execute categorySelection function when a new category selection is made
			categorySelectEl.onchange = function () {
				BuyersGuide.categorySelection();
			}

			// Execute subcategorySelection function when a new subcategory selection is made
			subcategorySelectEl.onchange = function () {
				BuyersGuide.subcategorySelection();
			}

			// Fetch subcategories if a pre-populated category selection exists onload
			if (categorySelectEl.value !== '0') {
				selectedCategoryId = categorySelectEl.value;
				BuyersGuide.fetchSubcategories();
			}
		},

		// A new category selection is made
		categorySelection : function () {

			// Store new selection value
			selectedCategoryId = categorySelectEl.value;

			// Hide results container <div>s and remove their HTML
			BuyersGuide.hideResults();

			// If a valid new category selection has been made
			if (selectedCategoryId !== '0') {

				// Ensure the no search results message is hidden
				noSearchResultsMessage.style.display = 'none';

				// Fetch relevant subcategories from the database
				BuyersGuide.fetchSubcategories();
			}
			
			// If the "- Select -" <option> has been selected, default the subcategory <select>'s HTML and
			// disable it, then add "buyersGuide_awaitingSelection" class from subcategory <select>'s <li>
			else {
				subcategorySelectEl.innerHTML = defaultSelectInnerHtml;
				subcategorySelectEl.setAttribute('disabled', 'disabled');
				addClass(subcategoryLiEl, "buyersGuide_awaitingSelection");
			}
		},

		// Fetch relevant subcategories from the database via an XMLHttpRequest
		fetchSubcategories : function () {

			// Make XMLHttpRequest
			Ajax.getText('../xhr/buyers-guide/get-subcategories-by-category-id.asp?id=' + selectedCategoryId,

				// Function executed on callback
				function (responseText) {

					// Eval to cast JSON response text into an object; in this case, an array of strings
					var subcategories = eval('(' + responseText + ')');

					// Populate subcategories <select> using subcategories object
					BuyersGuide.populateSubcategories(subcategories);
				}
			);
		},

		// Subcategories relevant to the category have been fetched, so populate subcategories <select>
		populateSubcategories : function (subcategories) {
			var innerHtml = '';

			// Loop through supplied subcategories array, adding each string therein as an <option> of the
			// subcategories <select>
			for (var i = 0; i < subcategories.length; i++) {

				// Add <option> to <select>, with value attribute equal to index of the subcategory, labelling it
				// as the subcategory name, for example, "Aeroacoustics"
				innerHtml += '<option value="' + subcategories[i]['id'] + '">' + subcategories[i]['subcategory'] + '</option>';
			}

			// Remove "buyersGuide_awaitingSelection" class from subcategory <select>'s <li>
			removeClass(subcategoryLiEl, "buyersGuide_awaitingSelection");

			// Append options to and undisable the <select>
			subcategorySelectEl.parentNode.innerHTML = '<label for="selectSubcategory">Subcategory</label> ' +
				'<select id="selectSubcategory" name="subcategory">' +
				defaultSelectInnerHtml + innerHtml + '</select>';

			// If there's one bug which drives me insane, it's IE 6's and 7's inability to modify the innerHTML of a <select>
			// element. It means you need to modify a parent element, and in doing so, you're removing the select from the DOM
			// and thereby relinquishing node refrences and event handlers. Grrrr!!! This means we need to relocate the node
			// and then reassign the onchange event handler, as below.

			// Re-establish node reference and execute subcategorySelection function when a new subcategory selection is made
			subcategorySelectEl = $('selectSubcategory');
			subcategorySelectEl.onchange = function () {
				BuyersGuide.subcategorySelection();
			}
		},

		// A new subcategory selection is made
		subcategorySelection : function () {

			// Store new subselection ID
			selectedSubcategoryId = subcategorySelectEl.value;

			// Hide results container <div>s and remove their HTML
			BuyersGuide.hideResults();

			// If a valid new subselection has been made
			if (selectedSubcategoryId !== '0') {
	
				// If the no search results message is visible, show the AJAX loading icon
				if (noSearchResultsMessage.style.display == 'none') { 
					ajaxLoadingIconEl.style.display = 'block';
				}

				// Fetch company information
				BuyersGuide.fetchCompanyInformation();
			}
			
			// If the "- Select -" <option> has been selected, ensure the AJAX loading icon is hidden
			else {
				ajaxLoadingIconEl.style.display = 'none';
			}
		},

		// Fetch relevant company information from the database via an XMLHttpRequest
		fetchCompanyInformation : function () {

			// Make XMLHttpRequest
			Ajax.getText('../xhr/buyers-guide/get-companies-by-subcategory-id.asp?id=' + selectedSubcategoryId,

				// Function executed on callback
				function (responseText) {

					// Eval to cast JSON response text into an object
					var companyInformation = eval('(' + responseText + ')');

					// Display company information using company information object
					BuyersGuide.displayCompanyInformation(companyInformation);
				}
			);
		},

		// Display relevant company information
		displayCompanyInformation : function (companyInformation) {

			// Hide the AJAX loading icon
			ajaxLoadingIconEl.style.display = 'none';

			// If no company is found, display the no search results message
			if (!companyInformation) {
				noSearchResultsMessage.style.display = 'block';
				return;
			}

			// Hide the no search results message
			noSearchResultsMessage.style.display = 'none';

			// Define variables to contain tiered company information
			var goldCompanyInformation;
			var silverCompanyInformation;
			var bronzeCompanyInformation;

			// Display gold tier company information (if any)
			for (var i = 0; i < companyInformation.gold.length; i++) {
				goldCompanyInformation = companyInformation.gold[i];

				// Show the relevant results div
				if (i === 0) searchResultsGoldEl.style.display = 'block';

				searchResultsGoldEl.innerHTML +=
					'<div class="result">' +
						((goldCompanyInformation['imageFilename'] !== 'null') ? '<img src="../uploads/buyers-guide-images/' + goldCompanyInformation['imageFilename'] + '" alt="" />' : '') +
						'<div class="resultContent">' +
							'<h3><a href="company.asp?id=' + goldCompanyInformation['companyId'] + '">' + unescape(goldCompanyInformation['company']) + '</a></h3>' +
							'<span class="location">' + goldCompanyInformation['location'] + '</span>' + 
							((goldCompanyInformation['description'] !== 'null') ? '<p>' + truncateStrByNumOfWords(unescape(goldCompanyInformation['description']), 40) + '</p>' : '') +
							'<div class="resultFooter">' +
								'<a class="web" href="http://' + goldCompanyInformation['website'] + '" target="_blank">' + goldCompanyInformation['website'] + '</a>' +
								'<strong class="tel">' + goldCompanyInformation['phone'] + '</strong>' +
								'<a class="more" href="company.asp?id=' + goldCompanyInformation['companyId'] + '">more&hellip;</a>' +
							'</div>' +
						'</div>' +
					'</div>';
			}

			// Display silver tier company information (if any)
			for (i = 0; i < companyInformation.silver.length; i++) {
				var silverCompanyInformation = companyInformation.silver[i];

				// Show the relevant results div
				if (i === 0) searchResultsSilverEl.style.display = 'block';

				searchResultsSilverEl.innerHTML +=
					'<div class="result">' +
						((silverCompanyInformation['imageFilename'] !== 'null') ? '<img src="../uploads/buyers-guide-images/' + silverCompanyInformation['imageFilename'] + '" alt="" />' : '') +
						'<div class="resultContent">' +
							'<h3><a href="company.asp?id=' + silverCompanyInformation['companyId'] + '">' + unescape(silverCompanyInformation['company']) + '</a></h3>' +
							'<span class="location">' + silverCompanyInformation['location'] + '</span>' + 
							((silverCompanyInformation['description'] !== 'null') ? '<p>' + truncateStrByNumOfWords(unescape(silverCompanyInformation['description']), 40) + '</p>' : '') +
							'<div class="resultFooter">' +
								((silverCompanyInformation['website'] != undefined) ? '<a class="web" href="http://' + silverCompanyInformation['website'] + '" target="_blank">' + silverCompanyInformation['website'] + '</a>' : '') +
								((silverCompanyInformation['phone'] != undefined) ? '<strong class="tel">' + silverCompanyInformation['phone'] + '</strong>' : '') +
								'<a class="more" href="company.asp?id=' + silverCompanyInformation['companyId'] + '">more&hellip;</a>' +
							'</div>' +
						'</div>' +
					'</div>';
			}

			// Display bronze tier company information (if any)
			for (i = 0; i < companyInformation.bronze.length; i++) {
				var bronzeCompanyInformation = companyInformation.bronze[i];

				// Show the relevant results div
				if (i === 0) searchResultsBronzeEl.style.display = 'block';

				searchResultsBronzeEl.innerHTML +=
					'<div class="result">' +
						'<div class="resultContent">' +
							'<h3><a href="company.asp?id=' + bronzeCompanyInformation['companyId'] + '">' + unescape(bronzeCompanyInformation['company']) + '</a></h3>' +
							((bronzeCompanyInformation['description'] !== 'null') ? '<p>' + truncateStrByNumOfWords(unescape(bronzeCompanyInformation['description']), 40) + '</p>' : '') +
							'<div class="resultFooter">' +
								'<a class="more" href="company.asp?id=' + bronzeCompanyInformation['companyId'] + '">more&hellip;</a>' +
							'</div>' +
						'</div>' +
					'</div>';
			}
		},

		// Hide results container <div>s and remove their HTML
		hideResults : function () {
			searchResultsGoldEl.style.display = 'none';
			searchResultsSilverEl.style.display = 'none';
			searchResultsBronzeEl.style.display = 'none';
			searchResultsGoldEl.innerHTML = '';
			searchResultsSilverEl.innerHTML = '';
			searchResultsBronzeEl.innerHTML = '';
		}
	}
})();
