// This file assumes that the jQuery library has been loaded prior to this invocation
// Load logic when document finishes page load
$(document).ready( function(){
	// Set observer on onChange for the order by drop-down
	$('select#sort_options').change( function(){
		// Localize current element as jQuery object
		var jQElement = $(this);
		// Check the value
		if(		jQElement.val().length > 0 )
			jQElement.parent().submit();
	});// End sort_option over-ride
	$('input#retry_search_input,input#front_search_input,input.default_clear').focus( window.searchFocus ).blur( window.searchBlur );// End retry search input over-ride
	// Set=up our search form handlers
	$('form.search_form').submit( function(){
		// Check to see if we have our search value around
		if(		typeof(this.searchval) != 'undefined' ){
			// Pass the ball over to the url fixing function
			searchTerm( this.searchval.value );
			// Return false
			return false;
		}// End the url fix-up
		else
			return true;
	});// End search form over-ride
	// Set-up our non-blank search form hanldes
	$('form.noblank_search').submit( function(){
		// First indicate that our return result will be false
		var blnSubmitForm = true;
		// Loop over each match inside our form object
		$.each( $(this).find('input.noblank_field'), function(index,curField){
			// First see if we already have decided to leave the loop
			if(		blnSubmitForm == true
				&&	(	curField.value.length == 0
					||	curField.value.match(/\w/) == null
					)
				)
				blnSubmitForm = false;
		});// End for loop for blank fields
		// Return status to caller
		return blnSubmitForm;
	});// End non-blank search over-ride
	// Listener for the Product Search.
	$('input#search_input').keyup(function(event) {
		productSearchAutosuggest($(this).val());
	});
});// End document onReady over-ride

// Function: searchTerm; Takes in term and forwards current window to the target location
window.searchTerm = function( term ){
	// Really simple, we just need to encode our current string and redirect user to the target page
	var term = encodeURIComponent(term.replace(/^(\ ){1,}|(\ ){1,}$|\n|\r|\t|\<|\>/g,''));
	if( term.length > 0 ){
		window.location = '/search/'+term+'.html';
	}
	else{
		window.location = '/search.html';
	}
	return false;
}// End searchTerm

// Function: homepageSearch( form ); Takes the form object and will post the submission based on the value
window.homepageSearch = function( form ){
	// First validate our input
	if( form.searchval.value == form.searchval.defaultValue ){
		// Redirect to search page
		window.location = '/search.html';
		return false;
	}
	else if( form.searchval.value.length == 0 )
		return false;
	// Return good status
	return true;
}// End homepageSearch

// Function: clearSearch( DOMObject, Click ); Takes reference (this ptr) to the DOM object and will determine if we should reset the value
window.clearSearch = function ( DOMObject, Click ){
	// Validate that we have our state supplied
	if(		arguments.length < 2 )
		var Click = false;
	// Next determine what action we are doing
	if(		Click==false
	   	&&	(		DOMObject.value == null || DOMObject.value.length == 0 ) )
		DOMObject.value = DOMObject.defaultValue;
	else if(	Click==true
			&&	DOMObject.value== DOMObject.defaultValue )
		DOMObject.value='';
}// End clearSearch

// Function: searchBlur(); Expects to be called via the onBlur method
window.searchBlur = function(){
	// Localize jQuery element
	var jQElement = $(this);
	// Check element
	if(		jQElement.length == 1 ){
		// Check our value
		if(		jQElement.val().length == 0 ){
			// Reset value and update text color
			jQElement.val( jQElement.attr('defaultValue') ).css('color','#808080');
		}// End back-fill of the default value
	}// End structural integrity check
}// End searchBlur

// Function: searchFocus(); Expects to be called via the onFocus method
window.searchFocus = function(){
	// Localize jQuery element
	var jQElement = $(this);
	// Check element
	if(		jQElement.length == 1 ){
		// Check our value
		if(		jQElement.val() == jQElement.attr('defaultValue') ){
			// Clear value and assign actual typed text color
			jQElement.val('').css('color','#202020');
		}// End check for the default value
	}// End structural integrity check
}// End searchFocus

// Front-end search JavaScript components
// ==========================================================================================================================================
window.hideProductSearchAutosuggest = function() { // Hides the product search autosuggest elements.
	$("#product_search_results").remove();
	$("#product_search").hide();
	
	if($.browser.msie) { // Fix the padding issue in IE when the autosuggest div is hidden.
		$("form.search_form[name=keywordSearch]").css("padding-bottom", "0");
	}
}

// Function: productSearchAutosuggest( searchString ); Takes a string and runs a search against products/categories.
window.productSearchAutosuggest = function(searchString) {
	searchString = $.trim(searchString);
	
	if(searchString.length && (typeof(productSearchValue) == "undefined" || searchString != productSearchValue)) { // Do the search and render the results.
		productSearchValue = searchString;
		
		if($.browser.msie) { // Fix the padding issue in IE when the autosuggest div is shown.
			$("form.search_form[name=keywordSearch]").css("padding-bottom", "5px");
		}
		
		$("#product_search").show();
		$("#show_loading").show();
		
		$.ajax({
			type: "GET"
			,url: "/JSONSearch.cfm?searchString=" + encodeURI(searchString)
			,dataType: "json"
			,success: renderProductSearchAutosuggest
			,error: function(response) { // Clear any existing results and hide.
				hideProductSearchAutosuggest();
			}
		});
	}
	else if(!searchString.length) { // When blanked, clear any existing search results.
		hideProductSearchAutosuggest();
	}
}

// Function: renderProductSearchAutosuggest( data ); Callback for the ajax request started by productSearchAutosuggest. Renders search results in a dropdown.
window.renderProductSearchAutosuggest = function(data) {
	// The search string is returned in the result. If it doesn't match what is in the input, another request has already been made and this one should be ignored.
	if(typeof(productSearchValue) == "undefined" || productSearchValue == data.searchstring) {
		var displayHTML = '<table width="100%" id="product_search_results" border="0" cellspacing="0" cellpadding="0">';
		$("div#search_results").html("");
		
		if(data.categories.length || data.products.length) {
			$.each(data.categories, function() { // Loop through categories and render the HTML display;
				displayHTML += 	'<tr>' +
									'<td class="search_result" linkURL="' + this.link_url + '">' +
										'<img src="/site_images/categoryimg.gif" height="13">' + 
										this.name.replace(/"[b]"/gi, "<b>") + 
									'</td>' +
								'</tr>';
			});
		
			$.each(data.products, function() { // Loop through products and render the HTML display;
				var imagePath = this.thumbnail.length > 4? '/images/' + this.thumbnail : '/site_images/no_image.jpg'; // Use either the product image or a placeholder.
				
				displayHTML += 	'<tr>' + 
									'<td class="search_result" linkURL="' + this.link_url + '">' +
										'<img src="' + imagePath + '" style="float:left" width="35">' +
										'(' + this.item_number + ')' + ' From ' + this.vendor + '<br />' + this.description.replace(/"[b]"/gi, "<b>") +
									'</td>' +
								'</tr>';
			});
		}
		else { // If no results are found, hide the product search autosuggest.
			hideProductSearchAutosuggest();
		}

		$("#show_loading").hide();
		$("div#search_results").html(displayHTML +  '</table>');
		
		$('#product_search_results td.search_result').bind("mouseenter", function() { // Manually add the hover class to make highlighting work in IE.
			$(this).addClass("search_result_hover");
		});
		
		$('#product_search_results td.search_result').bind("mouseleave", function() { // Manually remove the hover class to make unhighlighting work in IE.
			$(this).removeClass("search_result_hover");
		});
		
		$('div#product_search').bind("mouseleave", function() { // Hide the product search autosuggest menu after the mouse leaves it.
			hideProductSearchAutosuggest();
		});
		
		$('#product_search_results td.search_result').click(function() {
			window.location = $(this).attr("linkURL");
		});
	}
}