var prefixes = new Array();


function TypeSuggestions( addressesFromServer, prefix ) {
    if ( addressesFromServer ) {
        this.townShips = new Array();
        for ( var town in addressesFromServer ) {
            this.townShips[this.townShips.length] = town;
        }
        this.addressesFromServer = addressesFromServer;
        this.init( addressesFromServer, prefix );
    } else {
        this.notRequest(prefix);
    }
}

TypeSuggestions.prototype.init = function( addressesFromServer, prefix ) {
	if ( this.townShips && prefix && addressesFromServer != undefined ) {
				if ( $(prefix+"_townShipHidden") ) $(prefix+"_townShipHidden").value = addressesFromServer["selectedTown"];
				var streetId = prefix + "_street";
				$( streetId ).observe('click' , function(e) {
						prefix = this.prefix;
				}.bind(this));
				var radiosText = '';
				var citiesRadiosId = prefix + "_citiesRadios";
				var aLoaderId = prefix + "_aLoader";
				$(citiesRadiosId).innerHTML = radiosText;
				$(aLoaderId).style.display = "none";

				if ( addressesFromServer["pieces"] == 1 ) {
						var strId = prefix + "_street";
						$(strId).focus();
						var townId = prefix + "_town";
						$(prefix+"_outTown").innerHTML = addressesFromServer["selectedTown"];
						$(townId).disabled = "disabled";
						$(townId).removeClassName("disabled");
						var oneTownId = prefix + "_oneTown";
						$(oneTownId).style.display = "none";
						enablingFields(prefix);
						townShipName = addressesFromServer["selectedTown"];
				} else
				if ( addressesFromServer["pieces"] > 1 ) {
						$(prefix+"_outTown").innerHTML = ""
						var ctsRowId = prefix + "_ctsRow";
						var strAct = prefix + "_street";
						if ( $(ctsRowId)) $(ctsRowId).style.display = "block";

						var ctsId = prefix + "_cts";
						$(ctsId).style.display = "block";

						this.townShips.each(function(el, idx) {
								if( addressesFromServer && (addressesFromServer[el].length > 3) ) {
										radiosText += '<div class="city" id="'+ prefix +'cityDiv' + (idx+1) + '"><input type="radio" name="' + prefix + '_townName" id="'+ prefix +'city' + (idx+1) + '" class="radio ftt" value="' + el + '" /><label for="city' + (idx+1) + '" id="city'+ (idx+1) +'Label">' + el + '</label></div>';
								}
						});
						desablingFields( prefix )
						$(prefix + "_citiesRadios").innerHTML = radiosText;

						this.townShips.each(function(el, idy) {
								if ( $(prefix +'cityDiv'+(idy+1)) ) {
										$(prefix +'cityDiv'+(idy+1)).observe('click' , function(e) {
												$(prefix+"_outTown").innerHTML = this.down().value;
												$(prefix+"_oneTown").style.display = "none";
												$(prefix+"_cts").hide();
												enablingFields(prefix);
												townShipName = this.down().value;
												$(prefix + "_townShipHidden").value = townShipName;
												$(prefix+"_street").focus();
										})
								}
						});
				} else
				if ( (addressesFromServer["pieces"] == 0) || (addressesFromServer["pieces"] == "undefined") ) {
						this.notRequest(prefix);

				}

				if ( $(prefix + "_street") ) {
						$(prefix + "_street").observe('focus' , function(e) {
								this.prefix = prefix;
								townShipName = $(this.prefix + "_townShipHidden").value;
						}.bind(this));
				}
		}
}

TypeSuggestions.prototype.notRequest = function (prefix) {
		townShipName = "";
		var aloader = prefix + "_aLoader";
		var townId = prefix + "_town";
		var outTownId = prefix + "_outTown";
		var oneTownId = prefix + "_oneTown";


		$(aloader).style.display = "none";
		$(outTownId).style.display = "none";
		$(oneTownId).style.display = "block";
		$(townId).style.display = "block";

		$(townId).value = ""
		$(townId).disabled = ""
		enablingFields(prefix);


}

TypeSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl, bTypeAhead) {
		var aSuggestions = [];
		var sTextboxValue = oAutoSuggestControl.textbox.value;
		if (  (townShipName != "") ){
            //search for matching townShip
            //alert(townShipName)
            for (var i=0; i < this.addressesFromServer[townShipName].length; i++) {
                if (this.addressesFromServer[townShipName][i].toLowerCase().indexOf(sTextboxValue.toLowerCase()) == 0) {
                    aSuggestions.push(this.addressesFromServer[townShipName][i]);
                }
            }
        }

		//provide suggestions to the control
		oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
};









function AutoSuggestControl(oTextbox, oProvider) {

		/*The currently selected suggestions. int*/
		this.cur = -1;

		/*The dropdown list layer.*/
		this.layer = null;

		/*SuggestionProvider*/
		this.provider = oProvider;

		/*The textbox to capture. HTMLInputElement*/
		this.textbox = oTextbox;

		//initialize the control
		this.init();

		this.provider.init();
}

/*Suggestions An array of suggestion strings. bTypeAhead If the control should provide a type ahead suggestion.*/
suggestErrorMsg = "Ilyen közterület nem található az adatbázisunkban! Kérjük, ellenőrizze a beírt utcanevet, ha helyesen gépelte be folytassa a munkát, ha elírta kérjük, javítsa!";
AutoSuggestControl.prototype.autosuggest = function (aSuggestions, bTypeAhead) {
		if (aSuggestions.length > 0) {
				//this.layer.style.borderColor = 'black';
				if (bTypeAhead) {
					 this.typeAhead(aSuggestions[0]);
				}
				this.showSuggestions(aSuggestions);
		} else {
				this.layer.style.height = '110px';
				//this.layer.style.borderColor = 'red';
				this.layer.innerHTML = suggestErrorMsg;
				//this.layer.style.visibility = "hidden"
				//this.hideSuggestions();
		}
};

AutoSuggestControl.prototype.createDropDown = function () {

		var oThis = this;

		//create the layer and assign styles
		this.layer = document.createElement("div");
		this.layer.className = "suggestions";
		this.layer.style.display = "none";
		this.layer.style.width = this.textbox.offsetWidth;

		//when the user clicks on the a suggestion, get the text (innerHTML) and place it into a textbox
		this.layer.onmousedown =
		this.layer.onmouseup =
		this.layer.onmouseover = function (oEvent) {
				oEvent = oEvent || window.event;
				oTarget = oEvent.target || oEvent.srcElement;

				if (oEvent.type == "mousedown" && (oTarget.firstChild.nodeValue != suggestErrorMsg)) {
						oThis.textbox.value = oTarget.firstChild.nodeValue;
						oThis.hideSuggestions();
				} else if (oEvent.type == "mouseover") {
						oThis.highlightSuggestion(oTarget);
				} else {
						oThis.textbox.focus();
				}
		};

		document.body.appendChild(this.layer);
};

/*return The left coordinate of the textbox in pixels.*/
AutoSuggestControl.prototype.getLeft = function () {

		var oNode = this.textbox;
		var iLeft = 0;

		while(oNode.tagName != "BODY") {
				iLeft += oNode.offsetLeft;
				oNode = oNode.offsetParent;
		}

		return iLeft;
};

/*return The top coordinate of the textbox in pixels. */
AutoSuggestControl.prototype.getTop = function () {

		var oNode = this.textbox;
		var iTop = 0;

		while(oNode.tagName != "BODY") {
				iTop += oNode.offsetTop;
				oNode = oNode.offsetParent;
		}

		return iTop;
};

/*oEvent The event object for the keydown event.*/
AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {

		switch(oEvent.keyCode) {
				case 38: //up arrow
						this.previousSuggestion();
						break;
				case 40: //down arrow
						this.nextSuggestion();
						break;
				case 13: //enter
						this.hideSuggestions();
						break;
				case 27: //esc
						this.hideSuggestions();
						break;
				//case 16: //shift

		}
};

/*param oEvent The event object for the keyup event.  37 39 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent) {

		var iKeyCode = oEvent.keyCode;

		//for backspace (8) and delete (46), shows suggestions without typeahead
		if (iKeyCode == 8 || iKeyCode == 46) {
				this.provider.requestSuggestions(this, false);

		//non-character keys
		} else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
				//ignore
		} else {
				//request suggestions from the suggestion provider with typeahead
				this.provider.requestSuggestions(this, true);
		}
};

/*suggestion dropdown hide*/
AutoSuggestControl.prototype.hideSuggestions = function () { this.layer.style.display = "none"; };

/*Highlights the given node in the suggestions dropdown.*/
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {

		for (var i=0; i < this.layer.childNodes.length; i++) {
				var oNode = this.layer.childNodes[i];
				if (oNode == oSuggestionNode) {
						oNode.className = "current"
				} else if (oNode.className == "current") {
						oNode.className = "";
				}
		}
};

/*Initializes the textbox*/
AutoSuggestControl.prototype.init = function () {

		//save a reference to this object
		var oThis = this;

		//assign the onkeyup event handler
		this.textbox.onkeyup = function (oEvent) {

				//check for the proper location of the event object
				if (!oEvent) {
						oEvent = window.event;
				}

				//call the handleKeyUp() method with the event object
				oThis.handleKeyUp(oEvent);
		};

		//assign onkeydown event handler
		this.textbox.onkeydown = function (oEvent) {

				//check for the proper location of the event object
				if (!oEvent) {
						oEvent = window.event;
				}

				//call the handleKeyDown() method with the event object
				oThis.handleKeyDown(oEvent);
		};

		//assign onblur event handler (hides suggestions)
		this.textbox.onblur = function () {
				oThis.hideSuggestions();
		};

		//create the suggestions dropdown
		this.createDropDown();

		this.textbox.onfocus = function () {
				if ( oThis.textbox.value == "" ) {
						oThis.provider.requestSuggestions(oThis, false)
						oThis.textbox.value = "";
				}
		};


};

/*Highlights the next suggestion in the dropdown and places the suggestion into the textbox.*/
AutoSuggestControl.prototype.nextSuggestion = function () {
		var cSuggestionNodes = this.layer.childNodes;

		if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
				var oNode = cSuggestionNodes[++this.cur];
				this.highlightSuggestion(oNode);
				if ( oNode.firstChild ) this.textbox.value = oNode.firstChild.nodeValue;
		}
};

/*Highlights the previous suggestion in the dropdown and places the suggestion into the textbox.*/
AutoSuggestControl.prototype.previousSuggestion = function () {
		var cSuggestionNodes = this.layer.childNodes;

		if (cSuggestionNodes.length > 0 && this.cur > 0) {
				var oNode = cSuggestionNodes[--this.cur];
				this.highlightSuggestion(oNode);
				this.textbox.value = oNode.firstChild.nodeValue;
		}
};

/*Selects a range of text in the textbox. param iStart The start index (base 0) of the selection.
 param iLength The number of characters to select.*/
AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) {

		//use text ranges for Internet Explorer
		if (this.textbox.createTextRange) {
				var oRange = this.textbox.createTextRange();
				oRange.moveStart("character", iStart);
				oRange.moveEnd("character", iLength - this.textbox.value.length);
				oRange.select();

		//use setSelectionRange() for Mozilla
		} else if (this.textbox.setSelectionRange) {
				this.textbox.setSelectionRange(iStart, iLength);
		}

		//set focus back to the textbox
		//this.textbox.focus();
};

/*Builds the suggestion layer contents, moves it into position, and displays the layer.
 aSuggestions is an array of suggestions for the control.*/
AutoSuggestControl.prototype.showSuggestions = function (aSuggestions) {

		var oDiv = null;
		this.layer.innerHTML = "";

		for (var i=0; i < aSuggestions.length; i++) {
				oDiv = document.createElement("div");
				oDiv.appendChild(document.createTextNode(aSuggestions[i]));
				this.layer.appendChild(oDiv);
		}

		this.layer.style.left = this.getLeft() + "px";
		this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
		this.layer.style.display = "block";

};

/*Inserts a suggestion into the textbox, highlighting the suggested part of the text.*/
AutoSuggestControl.prototype.typeAhead = function (sSuggestion) {

		//check for support of typeahead functionality
		if (this.textbox.createTextRange || this.textbox.setSelectionRange){
				var iLen = this.textbox.value.length;
				this.textbox.value = sSuggestion;
				this.selectRange(iLen, sSuggestion.length);
		}
};
