﻿// Class SearchBar

// searchResultsPage: Selector - go button behavior changes based on current page
// form: Selector - to prevent default form behavior
// searchField: Selector - the text field for address
// goBtn: Selector - go button next to text field
// checkboxes: Selector - filter checkboxes
// advancedToggle: Selector - what makes the bar open and close
// toggedDiv: Selector - the bit that toggles

BenefulMap.SearchBar = Class.extend({
	init: function(form, keywordField, searchField, goBtn) {
        // Properties
        this.mapsForm = $(form).eq(0);
    		this.keywordField = keywordField;
        this.searchField = searchField;
        this.goBtn = goBtn;
        this.defaultAddressText = BenefulMap.Constants.Strings.ADDRESS_FIELD_TEXT;
        
        // Methods
        this.autocompleteListener();
        this.searchFieldListener();
        this.toggleListener();
        this.enterKeyListener();
        this.goBtnListener();
        this.searchFieldValidatorListener();
	},
	getDefaultAddressText: function() {
	   return this.addressText;
	},
	getMapsForm: function() {
	   return this.mapsForm;
	},
	getKeywordField: function() {
	   return this.keywordField;
	},
	getSearchField: function() {
	   return this.searchField;
	},
	getLocationField: function() {
	   return this.searchField;
	},
	getKeywordField: function() {
	   return this.keywordField;
	},
	getGoBtn: function() {
	   return this.goBtn;
	},
	getAdvancedToggle: function() {
	   return this.advancedToggle;
	},
	getToggledDiv: function() {
	   return this.toggledDiv;
	},
	autocompleteListener: function() {
		var self = this;
		$(self.getKeywordField()).autocomplete({
			source: function(request, response)
			{
				if(request.term.length <= 2) {
					var filteredCategories = $.grep(globalAutocompleteCategories, function(item) {
						item = item.toLowerCase();
						return(item.startsWith(request.term.toLowerCase()));
					});
					
					response($.map(filteredCategories, function(item) {
						var obj = {};
						obj.label = item;
						obj.value = item;
						return obj;
					}));
				}
				else {
					if($(self.getLocationField()).val() !== BenefulMap.Constants.SEARCH_LOCATION_DEFAULT_VALUE) {
						WagWorld.Web.AjaxUtility.GetSpotNamesByKeywordAndLocation(request.term, $(self.getSearchField()).val(), function(result) {
							var keywordResults = result.value;
							
							var filteredCategories = $.grep(globalAutocompleteCategories, function(item) {
								item = item.toLowerCase();
								return(item.startsWith(request.term.toLowerCase()));
							});
							
							var mergedArray = filteredCategories.concat(keywordResults);
							
							response($.map(mergedArray, function(item) {
									var obj = {};
									obj.label = item;
									obj.value = item;
									return obj;
								}));
						});
					}
				}
			}
		});
		$(self.getLocationField()).autocomplete({
			source: function(request, response)
			{
				var filteredCities = $.grep(globalAutocompleteCities, function(item) {
					item = item.toLowerCase();
					return(item.startsWith(request.term.toLowerCase()));
				});
				
				response($.map(filteredCities, function(item) {
					var obj = {};
					obj.label = item;
					obj.value = item;
					return obj;
				}));
			}
		});
		// Adding classes to autocompletes for styling

		$(self.getKeywordField()).autocomplete('widget').addClass('keyword-search-autocomplete');

		$(self.getLocationField()).autocomplete('widget').addClass('location-search-autocomplete');
	},
	searchFieldListener: function() {
	    var self = this;
	    $(this.getKeywordField())
	    .focus(function()
	    {
	    	if($(this).val() === BenefulMap.Constants.SEARCH_KEYWORD_DEFAULT_VALUE)
	    		$(this).val('');
	    })
	    .blur(function()
    	{
	    	if($(this).val() === '')
	    		$(this).val(BenefulMap.Constants.SEARCH_KEYWORD_DEFAULT_VALUE);
	    });
	    $(this.getSearchField())
	    .focus(function()
	    {
	    	if($(this).val() === BenefulMap.Constants.SEARCH_LOCATION_DEFAULT_VALUE)
	    		$(this).val('');
	    })
	    .blur(function()
    	{
	    	if($(this).val() === '')
	    		$(this).val(BenefulMap.Constants.SEARCH_LOCATION_DEFAULT_VALUE);
	    });
	},
	toggleListener: function() {
        var self = this;
        $(this.getAdvancedToggle()).click( function(event) {
            event.preventDefault();
            $(this).toggleClass("hide-categories");
            $(self.getToggledDiv()).slideToggle();
        });
	},
	updateInputFieldListener: function() {
	   var self = this;
	   $(document).bind('update.searchbar', function(event, location) {
	      self.updateInputField(location); 
	   });
	},
	updateInputField: function(location) {
	  	console.log(location);
		if (location != "the U.S.") {
			$(this.getSearchField()).val(location);
		}
	},
	enterKeyListener: function() {
        var self = this;
        $(this.getSearchField() + ', ' + this.getKeywordField()).keypress(function(event) {
            if (event.which == 13) {
                event.preventDefault();
                $(self.getGoBtn()).click();
            }
        });
	},
	goBtnListener: function() {
		var self = this;
	   	$(this.getGoBtn()).click( function(event) {
	   	
			event.preventDefault();
			self.searchFilterValidator();
	   });
	},
	searchFilterValidator: function() {
		var self = this;
		var searchFieldText = $(this.getSearchField()).val();
		if($.trim(searchFieldText) === '' || searchFieldText === BenefulMap.Constants.SEARCH_LOCATION_DEFAULT_VALUE)
		{
			$(this.getSearchField()).css('border-color', '#F00');
		}
		else
		{
			if ($("body.find-spots")) {
				// TODO this should fire the search without reloading the page
				
				// var address = $(this.getSearchField()).val();
				// var keyword = $(this.getKeywordField()).val();
				// $(document).trigger('map.search', [address, keyword]);
				self.redirectToSearchResultsPage(); // redirect with ?search= in query string
			} else {
				self.redirectToSearchResultsPage(); // redirect with ?search= in query string
			}
			
		}
	},
	searchFieldValidatorListener: function() {
		var self = this;
		$(this.getSearchField()).keyup(function(event) {
			if($(this).val() !== '' || $(this).val() !== BenefulMap.Constants.SEARCH_LOCATION_DEFAULT_VALUE)
			{
				$(this).css('border-color', '#FFF');
			}
		});
	},
	redirectToSearchResultsPage: function() {
		console.debug('Redirect to search results page.');
		
		var loc = encodeURIComponent($(this.getSearchField()).val());
		
		var key = encodeURIComponent($(this.getKeywordField()).val());

		var newPage = BenefulMap.Constants.Snippets_PAGE_SEARCH_RESULTS;
		var pageContext = $("#page-context-wrap input").val();

		console.info('Location: ' + loc + '. Keyword: ' + key + '. Page Context: ' + pageContext);

		newPage = newPage.replace("%LOC%", loc);
		newPage = newPage.replace("%KEY%", key);
		newPage = newPage.replace("%REF%", pageContext);

		window.location = newPage;
    }
});
