var SubcategoriesSearch = new Array();

// load autocomplete script if not loaded
//if(typeof $.ajaxAutocompleter == 'undefined') {
//	$.getScript('se/jquery.ajax_autocompleter.js');
//}

var AutocompleteSearch = {};
AutocompleteSearch.search_term_not_selected_ac = true;  // flag showing if the current term was selected using the autocomplete
AutocompleteSearch.is_company = false;					// shows if the selected option is a company or not (a category instead if false);

$(document).ready( function () {
	
	// prepare elements for the autocomplete attachment
	$("#search_box input[type=text]").attr('id', 'search_textbox');
	$('#search_textbox').after('<input type="hidden" id="search_categ_seo" name="search_categ_seo" value="">');
	$('#search_categ_seo').after('<input type="hidden" id="search_textbox_hidden" name="search_textbox_hidden" value="">');
	
	$("#search_box select[name='subcat'] option").each(function(){
		if($(this).val() != 'null') 
		{
			SubcategoriesSearch[$(this).val()] = this;
			$(this).remove();
		}
	});
	
	$("#search_box select[name='classification']").change(function(){
		var selected = $(this).val();
		$("#search_box select[name='subcat'] option").each(function(){
			if($(this).val() != 'null') 
			{
				$(this).remove();
			}
		});

		for(var text in SubcategoriesSearch)
		{
			var parts = $(SubcategoriesSearch[text]).val().split('.');
			if(selected.replace(/\-/gi,'') == parts[0]) 
			{
				$("#search_box select[name='subcat'] option:last").after($(SubcategoriesSearch[text]));
			}
		}
	});
	
	$('#search_box form').unbind('submit');
	
	$("#search_box input[type='submit']").click(function() {
		
		var geo = $("#search_box select[name='geo'] option:selected").val();
		var link = 'http://' + location.hostname + '/' +'results.html';
		var search_text = $('#search_textbox').val();
		var cat = $("#search_box select[name='classification'] option:selected").val();
		if(typeof cat == 'undefined')
		{
			cat = 'null';
		}
		
		// company OR category selected with A/C?
		if( $('#search_textbox_hidden').val() == search_text ) {
			var seo = $('input[name=search_categ_seo]').val();
			if( seo != '' ) {
				if( AutocompleteSearch.is_company ) {
					if( (geo == 'null') && (cat == 'null') ) {
						// no filters selected, go to profile page
						var company_location = 'http://' + location.hostname + '/' + $('input[name=search_categ_seo]').val() + '.html';
//						alert(categ_location);
						window.location = company_location;
						return false;
					}
				} else {
					// district selected ?
					if( geo != 'null' ) {
						link += '/geo_' + geo;
						var classif_parts = seo.split('/');
						link += '/classification_' + classif_parts[classif_parts.length-1];
						link += '?sort=by-name-a-z';
						window.location = link;
					} else {
						var categ_location = 'http://' + location.hostname + '/' + $('input[name=search_categ_seo]').val() + '.html';
//						alert(categ_location);
						window.location = categ_location;
					}
					return false;
				}
				
			}
			
		}
		
		if(geo != 'null')
		{
			link += '/geo_' + geo;
		}
		if(typeof cat != 'undefined')
		{
			if(cat != 'null' )
			{
				var subcat = $("#search_box select[name='subcat'] option:selected").val();
				if(subcat != 'null')
				{
					var parts = subcat.split('.');
					link += '/classification_' + parts[1];
				}
				else
				{
					link += '/classification_' + cat;
				}
			}
		}
		var search_term = $("#search_box input[type='text']").val();
		if(search_term != '' && search_term!= 'Search')
		{
			link += '?search=' + search_term;
		}
		
		if(link == 'results.html' || link == 'results.html?')
		{
			alert('Please select an option to search by');
		}
		else
		{
			window.location = link;
		}
		return false;
	});
	
	$("#sort_box select[name='sort']").change(function(){
		 var form = this.form;
		 $(form).attr('action', location.href);
		 $(form).submit(); 
	});
});

$(window).load(function() {
	// attach autocomplete
	var ac_url = 'http://'+ location.hostname.toString()+'/index.html';
	var ac_opts = {
		listID: 'search_list',
		minChars: 3,
		frequency: 1200,
		loadingImgID: 'loader',
		highlightClass: 'autocomplete_highlight',
		listWidth: 350,
		listHeight: 250,
		listZIndex: 5000,
		hide_no_results: true,
		headers: {'X_AJAX_INFO':'autocomplete_search'},
		firstItemHighlighted: false,
		showDirectionsDiv: true,
		beforeXHRCallback : function() {
			// reset both flags
			AutocompleteSearch.search_term_not_selected_ac = true;
			AutocompleteSearch.is_company = false;	
		},
		updateElement: function(selectedLI) {
			try {
				var _this = window['search_textbox_autocomplete'];
				var crt_val;
				var seo_categ;
				if(_this.activeIndex) {
					crt_val = _this.listItems[_this.activeIndex].getAttribute("ac_value");
					seo_categ = _this.listItems[_this.activeIndex].getAttribute("id");
					AutocompleteSearch.is_company = _this.listItems[_this.activeIndex].getAttribute("company");
				} else {
					crt_val = selectedLI.getAttribute("ac_value");
					seo_categ = selectedLI.getAttribute("id");
					AutocompleteSearch.is_company = selectedLI.getAttribute("company");
				}
				
				if( !AutocompleteSearch.is_company ) {
					var crt_val_categs = crt_val.split('&raquo;');
					crt_val = crt_val_categs.pop();
				} else {
					// extract the company name from the value
					var crt_val_pieces = crt_val.split('<br/>');
					crt_val = crt_val_pieces[0].replace('<b>','').replace('</b>','');
				}
				
				var search_text = $.trim(crt_val);
				
				$('input[name=search_categ_seo]').val(seo_categ);
				$('input[name=search_textbox_hidden]').val(search_text); // hidden for validation
				
				if(_this.activeIndex) {
					_this.listItems[_this.activeIndex].setAttribute("ac_value", search_text);
				} else {
					selectedLI.setAttribute("ac_value", search_text);
				}
				// set the flag saying it was selected with A/C
				AutocompleteSearch.search_term_not_selected_ac = false;
				
				_this.updateElement(selectedLI);
			} catch(e) {}
		},
		onEnterCallback: function() {
			var _this = window['search_textbox_autocomplete'];
//			alert(typeof _this.activeIndex);
			if(typeof _this.activeIndex == 'undefined') {
				// submit form
				$("#search_box input[type='image']").click();
				return false;
			} else {
				(_this.opt['updateElement'])(_this.listItems[_this.activeIndex]);
				if( !AutocompleteSearch.search_term_not_selected_ac) {
					AutocompleteSearch.search_term_not_selected_ac = true;
				} else {
					$("#search_box input[type='image']").click();
				}
//				setTimeout(function(){$("#search_box input[type='image']").click();}, 300);
				return false;
			}		
		}
	};
	$('#search_textbox').defaultValue('Search');
	AutocompleteSearch.search_ac = new $.ajaxAutocompleter('search_textbox', ac_url, ac_opts);
});