
var GmapAutoComplete = Class.create();

GmapAutoComplete.prototype = {
	initialize: function (id, options) 
	{
	    // Get the field we're watching.
	    // It needs to be a valid field so throw an error if it's not valid or can't be found.
	    this.inputField = $(id);
	    if (!this.inputField)
	    {
	      	throw("AutoComplete requires a field id to initialize");
	    }
		
	    // Init variables
	    this.inputValue = "";		// input value 
	    this.inputValueLength = 0;	// input value length
	    this.suggestions = []; 		// suggestions array 
	    this.highlightIndex = 0;	// level of list selection 
		
	  
		// Set the use specified options
		this.options = options ? options : {};
		
		// These are the default settings
		this.options = Object.extend({
								valueSep:null,
							    minchars:1,
							    varname:"input",
							    className:"autocomplete",
							    delay:0,
							    offsety:-5,
							    fadeDuration: 0.3,
							    maxresults: 10,
							    useNotifier: true,
							    parentId: 'suggestionHolder',
							    layerId: 'suggestionLayer',
							    formId: 'searchForm'
							}, options || { });
  

	  	// Not everyone wants to use the Notifier. Give them the option	
		if (this.options.useNotifier)
	  	{
	    	this.inputField.addClassName('searchField');
	  	}

		// set keyup handler for field
		// and prevent AutoComplete from client
		var p = this;
	
		// NOTE: not using addEventListener because UpArrow fired twice in Safari
		this.inputField.onkeypress = function(ev){ return p.onKeyPress(ev); };
		this.inputField.onkeyup = function(ev){ return p.onKeyUp(ev); };
	  	this.inputField.onblur = function(ev){  p.clearSuggestions.bind(p).delay(0.2); };	
	  	this.inputField.setAttribute("AutoComplete","off");
	}, 

	// set responses to keypress events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// RETURN sets the current highlighted value
	// UP/DOWN move around the list
	
	onKeyPress: function (e) 
	{
		if (!e) e = window.event;
		var key	= e.keyCode || e.wich;
		switch(key)
		{
			case Event.KEY_RETURN:
				if($(this.options.layerId).visible())
				{
					this.setHighlightedValue();
				}
				Event.stop(e);
				break;
			case Event.KEY_TAB:
				this.setHighlightedValue();
				//Event.stop(e);
				break;
			case Event.KEY_ESC:
				this.clearSuggestions();
				break;
		}
		return true;
	},

	onKeyUp: function (e) 
	{
  		if (!e) e = window.event;
  		var key = e.keyCode || e.wich;

		if (key == Event.KEY_UP || key == Event.KEY_DOWN) 
		{
  			this.changeHighlight(key);
  			Event.stop(e);
  		}
  		else 
  		{
  			this.getSuggestions(this.inputField.value);
  		}
		return true;
  	},

  	getSuggestions: function(value) 
  	{
  		if(this.animation) return false;
  		if(value == this.inputValue) return false;
  	
		this.inputValue = value;
  	
  		// input length is less than the min required to trigger a request
  		// do nothing
	  	if (value.length < this.options.minchars)
	  	{
	  		this.suggestions = [];
	  		this.inputValueLength = value.length; 
	  		this.clearSuggestions();
	  		return false;
	  	}

  		this.inputValueLength = value.length ? value.length : 0;

  		// do new request
  		var p = this;
  		
  		clearTimeout(this.timer); // ajax id timer
  		this.timer = setTimeout( function () {p.googleSuggest(p.inputValue)}, this.options.delay);
  	
    	document.helper = this;	
  		return false;
	}, 


  	googleSuggest: function (input) 
  	{
	  	if (input != this.inputField.value) return false;
  	
	  	var p = this;
		var address = this.inputValue;
		var url = "http://maps.google.com/maps/suggest";
		var params = new Object();
		params.q = address;
		params.cp = 8; //cim vyssie cislo tym detailnejsie hladanie - kraj->mesto->mestska cast->ulica...
		params.ll = "48.69096,18.588867";   //boundary box
		params.spn = "14.282928,57.084961"; //boundary box
		params.hl = "sk";
		params.v = 2;
		params.json = "a";
		params.num = this.options.maxresults; //pocet vratenych vysledkov
		params.numps = 5; //????
		params.callback = "googleSuggestResponse";
		//https://maps-api-ssl.google.com/maps/suggest?q=brat&cp=4&ll=48.69096,19.511719&spn=28.617209,114.169922&hl=en&gl=&v=2&json=a&auth=4c19c758ZifrA0-9UmKFkX7oNpnPp84-PwU&src=1,2&num=10&numps=5&callback=_xdc_._1bgajchtgz
		//https://maps-api-ssl.google.com/maps/suggest?q=bra&cp=3&ll=48.69096,18.588867&spn=14.282928,57.084961&hl=en&gl=&v=2&json=a&auth=4c19c758ZifrA0-9UmKFkX7oNpnPp84-PwU&src=1,2&num=10&numps=5&callback=_xdc_._1ogajcrwh9
		new Ajax.Request(url, {
			method: 'GET',
			crossSite: true,
			parameters:params,
			onSuccess: function(transport) 
			{
				//nedaju sa vytiahnut data}
			}
			
		});
  	},

  	setSuggestions: function (req) 
  	{ 
		this.suggestions = req;
    	this.autocompleteId = 'ac_' + this.inputField.id;
    	this.createList(this.suggestions);
  	},
  
  	createList:	function(arr) 
  	{
	  	// clear list removal timeout
	  	this.killTimeout();
  	
  		// if no results, and showNoResults is false, do nothing
  		var itemCount = arr.length;
	  	if (itemCount == 0) 
	  	{
			this.clearSuggestions();  		
	  		return false;
	  	}
  	
  		// create holding div
  		var div	= createDOMElement('div', {id:this.autocompleteId});
  	
    	// create and populate ul
    	var ul	= createDOMElement('ul', {id:'ac_ul'});
    	var p 	= this; // pointer that we will need later on
    
    	var itemIndex = 1;
  		for (var j=0,al = arr.length; j < al; j++)
  		{
	        var output = this.createAddressString(arr[j]);
	        var li = createDOMElement('li', {}, output); // add the link element to a li element
	        li.onclick = function() { p.setHighlightedValue() };
	        li.onmouseover = function(index, event) {p.setHighlight(index);}.bind(null, j + 1);
	        ul.appendChild(li);
	  	}
	    
	    div.appendChild(ul); // add the newly created list to the div element
	    div.onmouseover 	= function(){ p.killTimeout() };
	    div.onmouseout 		= function(){ p.resetTimeout() };
	    
	    if($(this.autocompleteId)) $(this.autocompleteId).remove();
	    
	    $(this.options.parentId).appendChild(div);
	    $(this.options.layerId).show();
	    
	    // highlight first item
	    this.highlightIndex = 0;
	    this.setHighlight(0);
  	},
  	

  	createAddressString: function(address)
  	{
  		return address[0];
  		
  	},
  	
  	changeHighlight: function(key) 
  	{
  		var list = $("ac_ul");
    	if (!list) return false;
	
    	var n;
		if(key == Event.KEY_DOWN || key == Event.KEY_TAB)
    	{
    		n = this.highlightIndex + 1;
    	}
    	else
    	{
    		n = this.highlightIndex - 1;
    	}
	
    	n = (n > list.childNodes.length)? list.childNodes.length : ((n < 1)? 1 : n);	
    	this.setHighlight(n);
  	},

  	setHighlight: function(n) 
  	{ 
  		var list = $('ac_ul');
  	
  		if (!list) return false;
		if(n == 0) return false;
  	
  		if (this.highlightIndex > 0) this.clearHighlight();
  	
  		this.highlightIndex = Number(n);
  	
  		if(list.childNodes[this.highlightIndex-1] && !$(list.childNodes[this.highlightIndex-1]).hasClassName('highlight'))
  		{
  			$(list.childNodes[this.highlightIndex-1]).addClassName('highlight');
  		}
  	
  		this.killTimeout();
  	},

  	clearHighlight:	function() 
  	{
  		var list = $('ac_ul');
  	
  		if(!list) return false;
  	
  		if(this.highlightIndex > 0)
  		{
	  		if($(list.childNodes[this.highlightIndex-1]).hasClassName('highlight'))
	  		{
	  			$(list.childNodes[this.highlightIndex-1]).removeClassName('highlight');
	  		}
  			this.highlightIndex = 0;
  		}
  	
  	},

  	setHighlightedValue: function() 
  	{ 
  		// HERE WE NEED TO IMPLEMENT THE GMAIL LIKE SPLITTED VALUE
  		if (!this.suggestions[this.highlightIndex - 1]) return;
  		
  		var value = this.suggestions[this.highlightIndex - 1][0];
  		this.inputField.value = value;
  		this.inputValue = value;
  		
  		// move cursor to end of input (safari)
  		this.inputField.focus();
  		if(this.inputField.selectionStart)
  			this.inputField.setSelectionRange(this.inputValue.length, this.inputValue.length);
  			
  		this.clearSuggestions();
  		
  		gmap.find(value);
  	},
 
  	killTimeout: function() 
  	{
  		clearTimeout(this.toID);
  	},

  	resetTimeout: function() 
  	{
  		this.killTimeout();
  	},

	clearSuggestions: function () 
	{
	  	this.killTimeout();
    	if ($(this.autocompleteId))
    	{
    		this.animation = true;
    		Effect.Fade(this.options.layerId, {duration: this.options.fadeDuration, afterFinish: function() { this.animation = false; }.bind(this)} );
    	}
  	}
}

function googleSuggestResponse(results)
{
	if(results.length > 0)
	{
		var suggestions = results[3];
		gmapAutoComplete.setSuggestions(suggestions);
	}
	else
	{
		gmapAutoComplete.clearSuggestions();
	}
}

