// agAjaxSuggest
var agSuggester =
	new Class(
	{
		initialize:
			function(item, width, hidn, decal, autoSubmit, typeT9)
			{
				this.width = width;
				this.item = item;
				this.hidn = hidn;
				this.decal = (decal > 0 ? decal : 0);
				this.form = this.item.form; 
				this.autoSubmit = autoSubmit;

				this.hidn_save 	= "";
				this.item_save 	= "";
				this.typeT9		= typeT9;

				this.link = {};

				this.searchable = (_page == "index.php" | _page == "gadget.php"  | _page == "redirect.annuaire.php"  | _page == "ambiguous_loc_fr.php" | _page == "resultats.php" | _page == "home_ville.php" | _page == "resultats_refnat.php" | _page == "detail_refnat.php" | _page == "bien_ville_liste.php" | _page == "bien_ville_piece.php" | _page == "index_ville_alpha.php" | _page == "index_agence_alpha.php" | _page == "resultat_ville_alpha.php" | _page == "resultat_agence_alpha.php" ? false : true);

				// this.preload();

				this.buildResults();
				this.clearResults();

				this.item.addEvent("select",
					function(e)
					{
						var e = new Event(e);
					}.bind(this)
				);

				this.item.addEvent("keyup",
					function(e)
					{
						var e = new Event(e);

						if (e.key != "up" && e.key != "down" && e.key != "left" && e.key != "right" && e.key != "tab" && e.key != "enter" && e.key != "esc" && e.code != 17 && e.code != 16)
						{
							if (this.typeT9)
							{
								this.check_seizure(this.item);
							}
							
							this.search();
						}
					}.bind(this)
				);

				this.item.addEvent("keydown",
					function (e)
					{
						var e = new Event(e);

						switch(e.key)
						{
							case "up" :
								this.navigate("up");

								break;

							case "down" :
								this.navigate("down");

								break;

							case "enter" :
								if (this.open)
								{
									this.setItem(this.current);
								}

								break;

							case "tab" :
								if (this.open)
								{
									this.clearResults();
								}

								break;

							case "esc" :
								if (this.open)
								{
									this.clearResults();
									this.item.blur();
								}

								break;

							default :
								break;
						}
					}.bind(this)					
				);
				
				//Ambiguous page // We check if we have values in Loc_name and loc_ key fields
				
				if (this.item.value != LABEL['DEFAULT_LOCALITY'] && this.hidn.id != '')
				{
				/*	//this.enableSearch();			
					this.hidn.value = this.item.value;
				*/	
					this.item_save  = this.item.value;
					//this.item_save 	= "";
					
					this.enableSearch();
				}
			},
			
		check_seizure:
			function(myfield)
			{
				value = myfield.value;
				
				carac = value.substr(value.length - 1, 1);
				
				//$('villes').setHTML(value.length+" :: Dernier caractère: >"+carac+"<");
				
				//var carac_regexp = new RegExp("[ a-zA-Z0-9\'\-\u00c0-\u00ff]");
				var carac_regexp = new RegExp("[- a-zA-Z0-9\'\u00C0-\u00FF]");
				if (carac_regexp.test(carac)==false)
				{
					//alert("Erreur sur : >"+carac+"<");
					//this.deletelastcaract(myfield);
				}
			},

			
		deletelastcaract:
			function(myfield)
			{
				value = myfield.value;
				
				lastcaract = value.substr(value.length - 1, 1);
				myfield.value = value.substr(0, value.length - 1);
			},			

		preload:
			function()
			{
				path = "/images/search/";

				this.images = new Array();

				this.images[0] = new Image();
				this.images[1] = new Image();
				this.images[2] = new Image();

				/*
				this.images[3] = new Image();

				this.images[0].src = path + "search_" + (_page == "zzindex.php" ? "zz" : _site) + ".gif";
				this.images[1].src = path + "search_" + (_page == "zzindex.php" ? "zz" : _site) + "_on.gif";
				this.images[2].src = path + "search_" + (_page == "zzindex.php" ? "zz" : _site) + "_off.gif";
				*/
				
				// pages "ville"
				if (_page == "home_ville.php")
				{
					this.images[0].src = path + "bt_search_ville.gif";
					this.images[1].src = path + "bt_search_ville_on.gif";
					this.images[2].src = path + "bt_search_ville_off.gif";
				}

				// this.images[3].src = "http://dev.images.ressources.logic-immo.com/images/fields/loading_search.gif";
			},

		getPositions:
			function()
			{
				dimensions = this.item.getCoordinates();

				this.h = dimensions.height;
				this.w = dimensions.width;
				this.l = dimensions.left;
				this.t = dimensions.top + this.h;
			},

		buildResults:
			function()
			{
				this.container = $(this.item.getProperty("id") + "_suggestion");
			},

		buildShadow:
			function()
			{
				dimensions_container = this.container.getCoordinates();
				dimensions_item = this.item.getCoordinates();

				h = dimensions_container.height + 7;
				w = this.width.toInt() + 2;
				l = dimensions_item.left - this.decal - 9 - (window.ie8 ? 1 : 0);
				t = dimensions_item.top + 22;

				this.shadow = $(this.item.getProperty("id") + "_shadow");

				this.shadow.setStyle("top", t + "px");
				this.shadow.setStyle("left", l + "px");

				ht = Math.ceil(h / 2);
				hb = h - ht;

				ctl = $(this.item.getProperty("id") + "_tl");
				ctr = $(this.item.getProperty("id") + "_tr");
				cbl = $(this.item.getProperty("id") + "_bl");
				cbr = $(this.item.getProperty("id") + "_br");

				// resize only when needed
				if (ctl.getStyle("height").toInt() != ht)
				{
					ctl.setStyle("height", ht + "px");
				}

				if (ctr.getStyle("height").toInt() != ht)
				{
					ctr.setStyle("height", ht + "px");
				}

				if (cbl.getStyle("height").toInt() != hb)
				{
					cbl.setStyle("height", hb + "px");
				}

				if (cbr.getStyle("height").toInt() != hb)
				{
					cbr.setStyle("height", hb + "px");
				}

				if (this.shadow.getStyle("height").toInt() != h)
				{
					this.shadow.setStyle("height", h + "px");
				}

				// show
				this.shadow.setStyle("display", "block");
			},

		search:
			function()
			{
				value = this.item.value;

				if (value.length >= 2)
				{
					//alert('COUNT IS OK ->'+this.typeT9);
					if (this.typeT9 == 1)
					{
						//$('villes').setHTML('COUNT IS OK ->'+this.typeT9+" - "+this.item.id+" - "+this.hidn.id);
						this.enableSearch();
						this.hidn.value = value;
						//this.item_save  = value;
					}

					/** this.cancel(); **/
					this.send(value);
				}
				else
				{
					this.clearResults();

					if (this.typeT9==1)
					{
						//this.disableSearch();
						this.hidn.value = "";
						this.item_save = "";
					}
				}
			},

		cancel:
			function()
			{
				if (this.ajax)
				{
					this.ajax.cancel();

					/*
					if (this.ajax.running)
					{
						this.ajax.cancel();
					}
					*/
				}
			},

		send:
			function(value)
			{
				value = value.toUpperCase();
				value = value.replace(/-/g, " ");

				if (value.length > 5)
				{
					value = this.formatValue(value);

					mode = "sql";
				}
				else
				{
					if (isNaN(value) && value.length < 3)
					{
						// specific case of French cities which name or postcode is 2 characters long
						if (_site == "fr" && value.length == 2)
						{
							cities = "AY|BU|BY|EU|FA|GY|OO|OZ|PY|RI|RY|SY|UR|US|UZ";
							pcodes = "2A|2B";

							if (cities.indexOf(value) > -1)
							{
								mode = "sql";
							}
							else
							{
								if (pcodes.indexOf(value) > -1)
								{
									mode = "txt";
								}
								else
								{
									return;
								}
							}
						}
						else
						{
							return;
						}
					}
					else
					{
						first_a = value.substr(0, 3);
						first_b = value.substr(0, 4);
						first_c = value.substr(0, 5);

						if (_site == "fr" && (first_a == "ST " || first_b == "STE " || first_c == "STES "))
						{
							value = this.formatValue(value);

							mode = "sql";
						}
						else
						{
							mode = "txt";
						}
					}
				}

				this.value = value;			
				
				switch (mode)
				{
					case "sql" :
						value = value.replace(/'/g, "''");
						url = _http + "ajax/get_localite_sql.php?site=" + _site + "&lang=" + _lang;

						break;
						
					case "txt" :
						value = value.replace(/'/g, "_");
						//value = srmtoupper(value);

						// url = _http + "ajax/t9/" + value.length + "/" + value.substring(0, 1).toUpperCase() + "/" + value.toUpperCase() + ".txt";
						url = _http + "ajax/t9/" + _lang + "/" + value.length + "/" + value.substring(0, 1) + "/" + value + ".txt";

						break;
				}

				this.cancel();

				this.ajax = new Json.Remote(url, { onComplete : function(data) { this.showResults(data) }.bind(this), onFailure : function() { var data = null; this.showResults(data) }.bind(this) });
				this.ajax.send(value);
			},

		formatValue:
			function(value)
			{
				if (_site == "fr")
				{
					first_c = value.substring(0, 3).toUpperCase();
					remains = value.substring(3, value.length);

					if (first_c == "ST ")
					{
						value = "SAINT " + remains;
					}

					first_c = value.substring(0, 4).toUpperCase();
					remains = value.substring(4, value.length);

					if (first_c == "STE ")
					{
						value = "SAINTE " + remains;
					}

					first_c = value.substring(0, 5).toUpperCase();
					remains = value.substring(5, value.length);

					if (first_c == "STES ")
					{
						value = "SAINTES " + remains;
					}
				}

				return value;
			},

		showResults:
			function(data)
			{
				this.clearResults();

				if (data != null && data.length > 0)
				{
					this.data = data;

					for (var i = 0; i < this.data.length; i ++)
					{
						element = this.data[i];

						this.addResult(i, element.lct_id, element.lct_level, element.lct_parent, element.lct_name, element.lct_post_code, element.lct_count);
					}

					this.level = "";

					this.count = data.length - 1;
					this.current = 0;
				}
				else
				{
					label = LABEL["NO_MATCH_FOUND"];

					this.container.adopt(new Element("p", { "class" : "empty" }).setText(label));

					this.count = -1;
					this.current = -1;
				}

				this.getPositions();

				this.container.setStyle("width", (this.width - 6) + "px");
				this.container.setStyle("top", this.t + "px");
				this.container.setStyle("left", (this.l - this.decal - 5 - (window.ie8 ? 1 : 0)) + "px");
				this.container.setStyle("display", "block");

				this.buildShadow();

				this.open = true;
			},

		addResult:
			function(index, id, level, parent_label, label, postcode, count)
			{
				level = (level > 2 ? 2 : level);
				

				if (this.container.getChildren().length == 0)
				{
					first = true;
					
					if (_site=="be")
					{
						this.container.adopt(new Element("p", { "class" : "header" }).setText(LABEL["LOCALITY_TYPE_BE_" + level]));
					}
					else
					{
						this.container.adopt(new Element("p", { "class" : "header" }).setText(LABEL["LOCALITY_TYPE_" + level]));
					}

					this.container.adopt(new Element("p", { "class" : "separator" }));
				}
				else
				{
					if (level != this.level)
					{
						if (_site=="be")
						{
							this.container.adopt(new Element("p", { "class" : "header" }).setText(LABEL["LOCALITY_TYPE_BE_" + level]));
						}	
						else
						{
							this.container.adopt(new Element("p", { "class" : "header" }).setText(LABEL["LOCALITY_TYPE_" + level]));
						}

						this.container.adopt(new Element("p", { "class" : "separator" }));
					}
				}

				className = (index == 0 ? "on" : "off");
				// alternative display
				if (isNaN(this.value) && this.value != "2A" && this.value != "2B")
				{
					label = "<span>" + this.value + "</span>" + label.substring(this.value.length, label.length);
				}
				else
				{
					switch (_site)
					{
						case "be" :
							// label = "<span>" + label + "</span>";

							postcode = "<span>" + this.value + "</span>" + postcode.substring(this.value.length, postcode.length);

							break;

						case "fr" :
							// label = "<span>" + label + "</span>";

							if (level.toInt() == 1)
							{
								// dom tom
								if ([971, 972, 973, 974, 975, 976, 984, 986, 987, 988].contains(postcode.toInt()))
								{
									if (this.value.length == 2)
									{
										postcode = "<span>" + postcode.substr(0, 2) + "</span>" + postcode.substr(2, 1);
									}
									else
									{
										postcode = "<span>" + postcode + "</span>";
									}
								}
								else
								{
									postcode = "<span>" + postcode.substr(0, 2) + "</span>";
								}
							}
							else
							{
								postcode = "<span>" + this.value + "</span>" + postcode.substring(this.value.length, postcode.length);
								//postcode = "<span>" + label + "</span>" + postcode.substring(this.value.length, postcode.length);
							}

							break;
					}
				}

				switch (_site)
				{
					case "be" :
						if (level.toInt() > 1)
						{
							label = label + " (" + postcode + ")";
						}

						break;

					case "cz" :
						if (level.toInt() > 0)
						{
							label = label + " (" + parent_label + ")";
						}

						break;

					case "fr" :
						switch (level.toInt())
						{
							case 0 :
								label = label;

								break;

							/*
							case 1 :
								label = label + " (" + postcode.substr(0, 2) + ")";

								break;
							*/

							default :
								label = label + " (" + postcode + ")";

								break;
						}

						break;

					default :
						break;
				}

				link = new Element("a", { "id" : "entry" + index, "class" : className, "href" : "javascript:void(0)" }).setHTML(label);

				if (window.ie)
				{
					link.addEvent("click", function(e) { var event = new Event(e); this.setItem(index) }.bind(this));
				}
				else
				{
					link.addEvent("click", function(e) { this.setItem(index) }.bind(this));
				}

				link.addEvent("mouseover", function() { this.setCurrent(index) }.bind(this));

				this.container.adopt(new Element("p").adopt(link));

				this.level = level;
			},

		clearResults:
			function()
			{
				this.cancel();

				this.open = false;

				this.container.empty();
				this.container.setStyle("display", "none");

				if (this.shadow)
				{
					this.shadow.setStyle("display", "none");
				}
			},

		setItem:
			function(index)
			{
				this.cancel();

				if (this.count == -1)
				{
					return;
				}

				element = this.data[index];

				this.hidn_save = element.lct_id + "_" + element.lct_level;

				switch (_site)
				{
					case "be" :
						if (element.lct_level.toInt() == 2)
						{
							this.item_save = element.lct_name + " (" + element.lct_post_code + ")";
						}
						else
						{
							this.item_save = element.lct_name;
						}

						break;

					case "fr" :
						switch (element.lct_level.toInt())
						{
							case 0 :
								this.item_save = element.lct_name;

								break;

							case 1 :
								// dom tom
								if ([971, 972, 973, 974, 975, 976, 984, 986, 987, 988].contains(element.lct_post_code.toInt()))
								{
									this.item_save = element.lct_name + " (" + element.lct_post_code + ")";
								}
								else
								{
									this.item_save = element.lct_name + " (" + element.lct_post_code.substr(0, 2) + ")";
								}

								break;

							default :
								this.item_save = element.lct_name + " (" + element.lct_post_code + ")";

								break;
						}

						break;

					default :
						this.item_save = element.lct_name;

						break;
				}

				this.hidn.value = this.hidn_save;
				this.item.value = this.item_save;

				if (_page != "redirect.annuaire.php" && _page != "resultats_agences.php" && _page != "resultats_agence_annonces.php" && _page != "ambiguous_fr.php")
				{
					this.item.focus();
				}
				else
				{
					this.item.blur();
				}

				this.clearResults();

				// cz homepage -> clears radio buttons
				if (_site == "cz" && _page != "redirect.annuaire.php")
				{
					window.frames[0].agMyMap.reset();

					if (_page != "index.php")
					{
						for (var i = 1; i < 4; i ++)
						{
							$("loc_key" + i).value = "";
						}
					}
				}

				/*
				if (_page == "index.php" || _page == "redirect.annuaire.php" || _page == "zzindex.php")
				{
					this.enableSearch();
				}
				*/
				
				if ($('go_search')){ //On valide la recherche que si le bouton existe
					//alert("button is here");
					this.enableSearch();
				}

				if (this.autoSubmit == "true")
				{
					$("loc_name_img_0").setProperty("src", this.images[3].src);

					this.form.submit();
				}
			},

		enableSearch:
			function()
			{
				if (this.searchable == false && $("go_search"))
				{
					// $("go_search").setProperty("src", this.images[0].src);
					$("go_search").setProperty("class", _site + "_search_on");

					// cz homepage -> call of search_cz() function
					if (_site == "cz")
					{
						this.link = new Element("a", { "id" : "link_search", "href" : "javascript:search_cz()", "target" : "_self" }).injectBefore($("go_search"));
					}
					else
					{
						this.link = new Element("a", { "id" : "link_search", "href" : "javascript:search()", "target" : "_self" }).injectBefore($("go_search"));
					}

					this.link.adopt($("go_search"));

					// new agLink(this.link, agLinks.length);

					this.searchable = true;
				}
				
			},

		disableSearch:
			function()
			{
				if (this.searchable == true)
				{
					this.link = $("link_search");

					img = $("go_search").clone();

					// img.setProperty("src", this.images[2].src);
					img.setProperty("class", _site + "_search");
					img.injectBefore(this.link);

					this.link.remove();

					this.searchable = false;
				}
			},

		getValue:
			function()
			{
				return this.item_save;
			},

		hasValue:
			function(index)
			{
				if (this.item_save != "")
				{
					return true;
				}
				else
				{
					return false;
				}
			},

		setDefault:
			function(hidn, item)
			{
				this.hidn_save = hidn;
				this.item_save = item;
			},

		addItem:
			function(value)
			{
				values = this.item.value.split(", ");
				values[values.length - 1] = value;

				this.item.value = values.join(", ") + ", ";
				this.item.focus();

				// this.clearResults();
			},

		setCurrent:
			function(index)
			{
				$("entry" + this.current).setProperty("class", "off");
				$("entry" + index).setProperty("class", "on");

				this.current = index;
			},

		navigate:
			function(direction)
			{
				if (this.count == -1 || this.open == false)
				{
					return;
				}

				switch (direction)
				{
					case "up" :
						if (this.current == 0)
						{
							return;
						}
						else
						{
							$("entry" + this.current).setProperty("class", "off");
							$("entry" + (this.current - 1)).setProperty("class", "on");

							this.current = this.current - 1;
						}

						break;

					case "down" :
						if (this.current == this.count)
						{
							return;
						}
						else
						{
							$("entry" + this.current).setProperty("class", "off");
							$("entry" + (this.current + 1)).setProperty("class", "on");

							this.current = this.current + 1;
						}

						break;
				}
			},

		isOpen:
			function()
			{
				return this.open;
			}
	});

