
var _changedElement = document.getElementById('areasdefault');
var _oldInputFieldValue = ""; 
var _busy = false;
var _currentInputFieldValue = ""; 
var _cacheSearchValue = "";
var _eventKeycode = ""; // event keycode...
var _areaIndex = -1; // currently hightlighted area index
var _areasDiv = null; // currently highlisted area div...
var _areasDivRows = -1; // completeDiv rows at time of keypress...
var _areaDivList = null; // completeDiv div list at time of keypress
var _areasDivRows2 = 5; 
var _divTag = "div"; 
var _spanTag = "span"; 
var _inputField = null; // Input field on form...
var _availableAreasDiv = null;
var _cursorUpDownPressed = false;  
var _resultCache = new Object(); 
var _lastKeyCode = -1; // Gets set on keyDown.
var _hasXMLHTTP = false; // Gets set to true if XMLHTTP Supported
var _selectedValue = null;
var _sizeAdjustment = 60;
var _timeoutAdjustment = 0; // timeout adjustment... gets adjusted over time...
var _linkText = " - ";	// text to link the area with it's long description.
var _form = null;
var _canSubmit = true;
var _singleDivHeight = 13;
var _areas = new Object();
var _areasCombo = new Object();
var _combosAreas= new Array();

function ChangeDropDown(level){
	dropDownParent='areaLevel_'+(level);
	dropDownChild='areaLevel_'+(level+1);
	selectedParent=document.getElementById(dropDownParent).options[document.getElementById(dropDownParent).selectedIndex].value;
	if (document.getElementById(dropDownChild)!=null)
	{
		clearCombo(dropDownChild);
		xajax_XajaxGetAreasForDropDown(selectedParent, this[dropDownChild].level, this[dropDownChild].sublevels, this[dropDownChild].saleFlag);
	}else{
		xajax_XajaxChangeAreasDropDown(selectedParent, level+1);
	}
	
}

function ChangeDropDownQS(level){
	dropDownParent='qsareaLevel_'+(level);
	dropDownChild='qsareaLevel_'+(level+1);
	selectedParent=document.getElementById(dropDownParent).options[document.getElementById(dropDownParent).selectedIndex].value;
	if (document.getElementById(dropDownChild)!=null)
	{
		clearCombo(dropDownChild);
		xajax_XajaxGetAreasForDropDownQS(selectedParent, this[dropDownChild].level, this[dropDownChild].sublevels, this[dropDownChild].saleFlag);
	}else{
		xajax_XajaxChangeAreasDropDown(selectedParent, level+1);
	}
	
}


function clearAreasCombos(){
	for ( i=0;i<_combosAreas.length;i++ ) {
		if (_combosAreas[i].parent>0)
		{
			document.getElementById(_combosAreas[i].name).selectedIndex=0;
		}else{
			
			clearCombo(_combosAreas[i].name);
		}
		
	}
}

function clearCombo(combo){
    if (document.getElementById(combo) != null ) {
	if(document.getElementById(combo).options.length>0){
		document.getElementById(combo).options.length = 0
		document.getElementById(combo).selectedIndex = 0;
		document.getElementById(combo).disabled = true;
	}
    }
}

function setCombo(combo, value)
{
	clearCombo(combo);
	
	xajax_XajaxGetAreasByIdForCombo(value, combo);	
}

function PopulateAreasCombo(combo){
	if (_areasCombo.Ars.length>0)
		{
			_combosAreas.push(combo);
			document.getElementById(combo).disabled = false;
			for(var i = 0; i < _areasCombo.Ars.length; i++)
			{
				document.getElementById(combo).options[i] = new Option(_areasCombo.Ars[i].N, _areasCombo.Ars[i].Id);
				
			}
		}	
}

function LimpiarFreeText(){
	
	if ( _inputField != null ) {
	  _inputField.value="";
	}
	if ( document.getElementById("hiddenAreaId") != null ) {
	  document.getElementById("hiddenAreaId").value=null;
	}
}

function LoadSearchPage( searchFormId, areaSearchId)
{
	if (typeof searchFormId == "undefined") {
    		searchFormId = "searchForm";
  	}
 	if (typeof areaSearchId == "undefined") {
    		areaSearchId = "areaSearch";
  	}

	xajax_XajaxRefreshCache();
	if (document.getElementById(areaSearchId) != null) {
	// setup the smart area tag.
		window.setTimeout("SetupSmartArea(document.getElementById('" + areaSearchId + "'), document.getElementById('" + searchFormId + "'));", 50);
	}
	window.onresize = resizeHandler;
}

function mensaje(datos){
	alert(datos);
}

function setCachedAreaDescription(area){
	_inputField.value = area;
}

function resizeHandler()
{
    try
    {
	    setCompleteDivSize();
	    PositionResults(_changedElement);
	}
	catch (e)
	{
	    alert("Error: " + e.message);
	}
}

function PositionResults(elem)
{
    try
    {
	    //var resultsDiv = document.getElementById('resultsDiv');
	    //resultsDiv.style.top = calculateOffsetTop(elem) + "px";
	    //resultsDiv.style.left = calculateOffsetLeft(elem) + elem.offsetWidth + "px";
	}
	catch (e)
	{
	}
}

function clearAreas(){
	_areas = new Object();
	_areas.Ars=new Array();
}

function clearAreasForCombo(parentValue){
	_areasCombo = new Object();
	_areasCombo.Ars=new Array();
	addAreaCombo(parentValue,'--- select ---', '--- select ---');
}

function addArea(id,na,ld){
  area= new Object;
  area.Id=id;
  area.N=na;
  area.LD=ld;
  _areas.Ars.push(area);
}

function addAreaCombo(id,na,ld){
   area= new Object;
  area.Id=id;
  area.N=na;
  area.LD=ld;
  _areasCombo.Ars.push(area);
}

function returnAreas(){
   ProcessAreas(_areas);
}

// This function uses AJAX to get areas back from the database that match the
// search criteria.
function GetAreas(searchCriterea)
{
	if (searchCriterea.length > 0)
	{
		xajax_XajaxGetAreas(searchCriterea);
	}
}


function ProcessAreas(areaCol)
{
	
	if(_timeoutAdjustment > 0) 
	{
		_timeoutAdjustment--;
	}
	
	var areaDiv = document.getElementById('completeDiv');
	
	displayAreas(areaDiv, areaCol.Ars);
	
	ProcessAreaDiv(areaDiv);
	
	if (_areasDivRows2 > 0) 
	{
		areaDiv.height = _singleDivHeight * _areasDivRows2 + 4;
		
		if (document.getElementById('completeFrame'))
		{
		    document.getElementById('completeFrame').style.height = areaDiv.height;
		}
	} 
	else 
	{
		hideCompleteDiv();
	}
}



// SetupSmartArea(document.getElementById('areaInput'));

SetupSmartArea = function(fld, frm)
{
	_inputField = fld;
	_form = frm;
	//setTimeout("AjaxMethods.GetCachedAreaDescription(SetAreaValue_Callback);", 10);
	if (document.getElementById("AJAX_numberOfResults")!=null &&
	    _inputField!=null)
	{
		xajax_XajaxGetCachedAreaDescription();
	}
	
	SetupPage();
}


// blurs focus, then sets focus again... 
// This is called when we press cursor up / cursor down...
function blurThenGetFocus()
{
	_cursorUpDownPressed = true;
	_inputField.blur();
	setTimeout("setInputFieldFocus();", 10);
	return;
}

// setup a keydown event...
function setupKeydown()
{
	if (document.createEventObject) 
	{
		var eventObj = document.createEventObject();
		eventObj.ctrlKey = true;
		eventObj.keyCode = 70;
		document.fireEvent("onkeydown", eventObj);
	}
}

function keyDownHandler(event)
{
	if(!event && window.event) 
	{
		event = window.event;
	}
	if (event) 
	{
		_lastKeyCode = event.keyCode;
	}
}

function setCompleteDivSize()
{
	if(_availableAreasDiv)
	{
	    var offsetLeft = calculateOffsetLeft(_inputField);
	    var offsetTop = calculateOffsetTop(_inputField);
	    // for IE only.
	    if(navigator && navigator.userAgent.toLowerCase().indexOf("msie") != -1)
	    {
		    offsetLeft += 2;
		    offsetTop += 2;
	    }
	    
		_availableAreasDiv.style.left = offsetLeft + "px";
		_availableAreasDiv.style.top = offsetTop + _inputField.offsetHeight - 1 + "px";
		_availableAreasDiv.style.width = calculateWidth() + "px";
		
		var frame = document.getElementById("completeFrame");
		if (frame)
		{
		    frame.style.left = _availableAreasDiv.style.left;
		    frame.style.top = _availableAreasDiv.style.top;
		    frame.style.width = _availableAreasDiv.style.width;
		}
	}
}

// calculate width of inputField... Note browser specific adjustments...
function calculateWidth()
{
    try
    {
	    if(navigator && navigator.userAgent.toLowerCase().indexOf("msie") == -1)
	    {
		    return _inputField.offsetWidth - 1 * 2;
	    }
	    else
	    {
		    return _inputField.offsetWidth;
	    }
	}
	catch (e)
	{
	}
}

function SetupPage()
{
	// Test to see if we can use callback.
	if (getXMLHTTP())
	{
		_hasXMLHTTP = true;
	}
	else
	{
		_hasXMLHTTP = false;
	}
	
	_inputField.autocomplete = "off";
	_inputField.onblur = onBlurHandler;
	
	if(_inputField.createTextRange) 
	{
		_inputField.onkeyup = new Function("return onKeyUpEvent(event);");
	} 
	else
	{
		_inputField.onkeyup = onKeyUpEvent;
	}
	
	_inputField.onsubmit = Submitting;
	
	_form.onsubmit = new Function("return submitForm();");
	
	if(navigator && navigator.userAgent.toLowerCase().indexOf("msie") != -1)
	{
	    // used so that drop downs do not shine through div in IE.
	    var frame = document.createElement("IFRAME");
	    frame.id = "completeFrame";
	    frame.border = 0;
	    frame.style.border = 0;
	    frame.style.borderColor = "white";
	    frame.style.visibility = "hidden";
	    frame.style.position = "absolute";
	    frame.style.backgroundColor = "white";
	    document.body.appendChild(frame);
	}
	
	_currentInputFieldValue = _inputField.value;
	_oldInputFieldValue = _currentInputFieldValue;
	_availableAreasDiv = document.createElement(_divTag);
	_availableAreasDiv.id = "completeDiv";
	_availableAreasDiv.style.borderRight = "black 1px solid";
	_availableAreasDiv.style.borderLeft = "black 1px solid";
	_availableAreasDiv.style.borderTop = "black 1px solid";
	_availableAreasDiv.style.borderBottom = "black 1px solid";
	_availableAreasDiv.style.zIndex = "22";
	_availableAreasDiv.style.paddingRight = "0";
	_availableAreasDiv.style.paddingLeft = "0";
	_availableAreasDiv.style.paddingTop = "0";
	_availableAreasDiv.style.paddingBottom = "0";
	_availableAreasDiv.style.textAlign = "left";
	setCompleteDivSize();
	_availableAreasDiv.style.visibility = "hidden";
	_availableAreasDiv.style.position = "absolute";
	_availableAreasDiv.style.backgroundColor = "white";
	
	
	document.body.appendChild(_availableAreasDiv);
	cacheResults("", null);
	setStyleForElement(_availableAreasDiv, "mAutoComplete");

	document.onkeydown = keyDownHandler;
	setupKeydown();
}

function onBlurHandler(event)
{
    try
    {
	    if (!event && window.event) 
	    {
		    event = window.event;
	    }
	    if (!_cursorUpDownPressed)
	    {
		    hideCompleteDiv();
		    // check if tab pressed...
		    if(_lastKeyCode == 9)
		    {
			    var index = _areaIndex;
			    var area = "";
			    var areasDiv = document.getElementById("completeDiv");
			    // if user has not selected anything, get the first value.
			    if (index == -1)
			    {
				    index = 0;				
			    }
    			
			    if (areasDiv.childNodes.length > index) 
			    {
				    area = findSpanValueForClass(areasDiv.childNodes[index], "uDisplaySpan");
				    _inputField.value = area;
				    // select this area id.
				    SelectAreaId(areasDiv.childNodes[index]);
			    }

			    _inputField.value = area;
			    _lastKeyCode = -1;
		    }
	    }
	    _cursorUpDownPressed = false
	}
	catch (e)
	{
		alert("Error: " + e.message);
	}
}

onKeyUpEvent = function(e)
{
	_eventKeycode = e.keyCode;
	_selectedValue = _inputField.value;
	keyHandler();
}

setInputFieldFocus = function()
{
	_inputField.focus();
}

function submitForm()
{
	// BeforeSubmit to be implemented somewhere else.
	if (typeof(BeforeAreaSubmit) == "function") 
	{ 
		_canSubmit = BeforeAreaSubmit();
	}	
	return _canSubmit;
}

// strip CR from string...
function stripCRFromString(va)
{
	for(var f = 0, oa = "", zb = "\n\r"; f < va.length; f++) 
	{
		if (zb.indexOf(va.charAt(f)) == -1) 
		{
			oa += va.charAt(f);
		} 
		else 
		{
			oa += " ";
		}
	}
	return oa;
}

// Find span value with className
function findSpanValueForClass(elem, cname)
{
    try
    {
	    var span = elem.getElementsByTagName(_spanTag);
	
	    if (span)
	    {
		    for(var f=0; f < span.length; ++f)
		    {
			    if(span[f].className == cname)
			    {
				    var value = span[f].innerHTML;
				    if(value == "&nbsp;") 
				    {
					    return "";
				    } 
				    else
				    {
					    return stripCRFromString(value);
				    }
			    }
		    }
	    }
	    else
	    {
		    return "";
	    }
    }
    catch (e)
    {
        alert("Error: " + e.message);
    }
}

// Return null if elem undefined...
function valueOfArea(elem)
{
	if (!elem) 
	{
		return null;
	}
	return findSpanValueForClass(elem, "uDisplaySpan");
}

// Return null if i undefined...
// otherwise return value of span resultSpan...
function valueOfDAutoComplete(elem)
{
	if (!elem) 
	{
		return null;
	}
	return findSpanValueForClass(elem, "resultSpan");
}

function hideCompleteDiv()
{
	document.getElementById("completeDiv").style.visibility = "hidden";
	if (document.getElementById("completeFrame"))
	{
	    document.getElementById("completeFrame").style.visibility = "hidden";
	}
	
	_canSubmit = true;
}

function showCompleteDiv()
{
	_canSubmit = false;
	document.getElementById("completeDiv").style.visibility = "visible";
	setCompleteDivSize();
	if (document.getElementById("completeFrame"))
	{
	    document.getElementById("completeFrame").style.visibility = "visible";
	}
}

// Caching returned area collections
function cacheResults(s, areaCol)
{
	_resultCache[s]= areaCol;
}

function keyHandler()
{
    try
    {
	    // 38 is up cursor key, 40 is down cursor key...
	    if(_eventKeycode == 40 || _eventKeycode == 38) 
	    {
		    blurThenGetFocus();
	    }

	    _currentInputFieldValue = _inputField.value;
	    if(handleCursorUpDownEnter(_eventKeycode) && _eventKeycode != 0)
	    { 
		    if (_currentInputFieldValue.length == 0)
		    {
			    hideCompleteDiv();
			    // clear the area if we clear the input box.
			    _inputField.title = "";
			    _changedElement = _inputField;
				if (document.getElementById("AJAX_numberOfResults")!=null)
				{
					xajax_XajaxChangePositionResultsForArea(14,'xajax_XajaxSelectSmartArea',0,"");
				}else{
					if (document.getElementById("areasdefault")!=null){
						document.getElementById("areasdefault").selectedIndex=0;
					}
					if ( document.getElementById("hiddenAreaId") != null ) {
						document.getElementById("hiddenAreaId").value=null;
					}
				}
		    }
	    }
	}
    catch (e)
    {
        alert("Error:" + e.message);
    }
}

function Submitting()
{
	return handleDiv();
}

function handleDiv()
{
	_busy = true;
	hideCompleteDiv();
	return true;
}

idkc = function()
{
	if(_inputField)
	{
		var val = _inputField.value;
		if (val != _selectedValue)
		{
			_eventKeycode = 0;
			keyHandler();
		}
		_selectedValue = val;
		setTimeout("idkc()" , 10);
	}
}

setTimeout("idkc()",10);

// Converts a string to a valid uri.. (spaces become %20, etc, etc..)
function escapeURI(La)
{
	if(encodeURIComponent) 
	{
		return encodeURIComponent(La);
	}
	if(escape) 
	{
		return escape(La);
	}
}

// If factor is 0, will return 150...
// If factor is 3, will return 250...
// If factor is 4, will return 450...
// If factor is X, will return 850...
function recalculateTimeout(factor)
{
	var newTime = 100;
	for (var o = 1; o <= (factor - 2) / 2; o++)
	{
		newTime = newTime * 2;
	}
	newTime = newTime + 50;
	return newTime;
}

// This function sets itself up and gets called over and over (timeout driven)
mainLoop = function()
{
	if(_oldInputFieldValue != _currentInputFieldValue)
	{
		if(!_busy)
		{
			var value = escapeURI(_currentInputFieldValue);
			var areas = _resultCache[_currentInputFieldValue];
			if (areas)
			{
				// Found in our cache...
				ProcessAreas(areas);
			}
			else
			{
				_timeoutAdjustment++;
				if(_hasXMLHTTP)
				{
					GetAreas(value);
				}
				else
				{
					// do nothing if we can not use callback.
				}
			}
			_inputField.focus()
		}
		_busy = false;
	}
	_oldInputFieldValue = _currentInputFieldValue;
	setTimeout("mainLoop()", recalculateTimeout(_timeoutAdjustment));
	return true;
}


// Call mainLoop() after 10 milliseconds...
setTimeout("mainLoop()", 10);

var mouseDown = function()
{
	selectEntry(valueOfArea(this));
	SelectAreaId(this);
	_busy = true;
	handleDiv();
}



var mouseOver = function()
{
	if(_areasDiv) 
	{
		setStyleForElement(_areasDiv, "fullDiv");
	}
	setStyleForElement(this,"overArea");
}


var mouseOut = function()
{
	setStyleForElement(this, "fullDiv");
}

// Called when cursor up/down pressed... selects new entry in completeDiv...
function highlightNewValue(index)
{
	_currentInputFieldValue = _cacheSearchValue;
	
	selectEntry(_cacheSearchValue);
	
	if (!_areaDivList || _areasDivRows <= 0) 
	{
		return;
	}
	
	showCompleteDiv();
	
	if (index >=_areasDivRows)
	{
		index =_areasDivRows - 1;
	}
	if(_areaIndex != -1 && index != _areaIndex)
	{
		setStyleForElement(_areasDiv, "fullDiv"); 
		_areaIndex = -1;
	}

	if (index < 0)
	{
		_areaIndex = -1;
		_inputField.focus();
		return;
	}

	_areaIndex = index;
	_areasDiv = _areaDivList.item(index);

	setStyleForElement(_areasDiv, "overArea");

	_currentInputFieldValue = _cacheSearchValue;

	selectEntry(valueOfArea(_areasDiv));
	// select area id.
	SelectAreaId(_areasDiv);
}

// returns false if cursor up / cursor down or enter pressed...
function handleCursorUpDownEnter(eventCode)
{
	if(eventCode == 40)
	{
		highlightNewValue(_areaIndex + 1);
		return false;
	}
	else if(eventCode==38)
	{
		highlightNewValue(_areaIndex - 1);
		return false;
	} 
	else if(eventCode == 13 || eventCode == 3)
	{
		return false;
	}
	return true;
}

// This function gets called for every keypress I make...
function ProcessAreaDiv(localCompleteDiv)
{
	var localInputField = _inputField;
	_areaIndex = -1;
	// This becomes the rows in list of areas...
	var areaDivs = localCompleteDiv.getElementsByTagName(_divTag);
	// # of rows in list...
	var availableAreas = areaDivs.length;
	_areasDivRows = availableAreas;
	_areaDivList = areaDivs;
	_areasDivRows2 = availableAreas;
	_cacheSearchValue = _currentInputFieldValue;
	
	if(_currentInputFieldValue == "" || availableAreas == 0)
	{
		hideCompleteDiv();
	}
	else
	{
		showCompleteDiv();
	}

	for (var f = 0; f < availableAreas; f++)
	{
		setStyleForElement(areaDivs.item(f), "fullDiv");
	}
	
	_areaIndex = -1;
	_areasDiv = null;

	var ab = false;
	switch(_eventKeycode)
	{
		// cursor left, cursor right, others??
		case 8:
		case 33:
		case 34:
		case 35:
		case 35:
		case 36:
		case 37:
		case 39:
		case 45:
		case 46:
			ab = true;
			break;
		default:
		// regular keypress ...
			
			break;
	}
	
	if(!ab && _areasDiv)
	{
		setStyleForElement(_areasDiv, "overArea");
	}
	else
	{
		_areaIndex = -1;
	}
}

function calculateOffsetLeft(elem)
{
	return IterativeAttributes(elem, "offsetLeft");
}

function calculateOffsetTop(elem)
{
	return IterativeAttributes(elem, "offsetTop");
}

function IterativeAttributes(elem, attr)
{
	var total = 0;
	
	while (elem)
	{
		total += elem[attr]; 
		elem = elem.offsetParent
	}
	
	return total;
}

function setStyleForElement(elem, name)
{
	SetSizeAdjustment();
	
	elem.className = name;

	switch (name.charAt(0))
	{
	case "m":
		elem.style.fontSize = "10px";
		elem.style.fontFamily = "verdana,sans-serif";
		elem.style.wordWrap = "break-word";
		break;
	case "p":
		elem.style.display = "block";
		elem.style.paddingLeft = "3";
		elem.style.paddingRight = "3";
		elem.style.height = _singleDivHeight + "px";
		elem.style.overflow = "hidden";
		break;
	case "f":
		elem.style.backgroundColor = "white";
		elem.style.color = "black";
		if(elem.displaySpan)
		{
			elem.displaySpan.style.color="green";
		}
		break;
	case "o":
		elem.style.backgroundColor = "#3366cc";
		elem.style.color = "white";
		if(elem.displaySpan)
		{
			elem.displaySpan.style.color = "white";
		}
		break;
	case "e":
		elem.style.color = "gray";
		break;
	case "d":
		elem.style.width = _sizeAdjustment + "%";
		elem.style.cssFloat = "left";
		break;
	case "r":
		elem.style.cssFloat = "right";
		elem.style.width = 100 - _sizeAdjustment + "%";
		elem.style.fontSize = "10px";
		elem.style.textAlign = "right";
		elem.style.color = "green";
		elem.style.paddingTop = "3px"
		elem.style.display = "none";
		break;
	case "u": // always hide the unformatted area.
		elem.style.display = "none";
		break;
	}
}

function SetSizeAdjustment()
{
	var inputWidth = calculateWidth();
	_sizeAdjustment = (inputWidth - 10) / inputWidth * 100;
}

function displayAreas(elem, areas)
{
	// First remove area elements.
	while(elem.childNodes.length > 0) 
	{
		elem.removeChild(elem.childNodes[0]);
	}

	// For each element in our list, we create:
	// <DIV (u) - mousedown/mouseover/mouseout fullDiv>
	//   <SPAN (ka) parentSpan>
	//     <SPAN (ua) displaySpan>
	//        <strong>Cab</strong>opino
	//			<SPAN (ea) extraSpan>
	//				- Marbella, Malaga
	//			</SPAN (ea)>
	//     </SPAN (ua)>
	//     <SPAN (ea) resultSpan>
	//        1
	//     </SPAN (ea)>
	//     <SPAN (ea) uIDSpan (hidden)>
	//        3
	//     </SPAN (ea)>
	//     <SPAN (ea) uDisplaySpan (hidden)>
	//        Cabopino
	//     </SPAN (ea)>
	//   </SPAN>
	//	 
	// </DIV (u)>
	
	if (areas != null && areas.length > 0)
	{		
		if ((!(_lastKeyCode == 13 && _canSubmit == false)) && (_lastKeyCode != -1))
		{
			// make sure we do not display area if we only have one and it is already selected.
			if ((areas.length == 1 && areas[0].N != _selectedValue) || areas.length > 1)
			{
				for(var f = 0; f < areas.length; ++f)
				{
					var areaDiv = document.createElement(_divTag);
					setStyleForElement(areaDiv, "fullDiv");
					areaDiv.onmousedown = mouseDown;
					areaDiv.onmouseover = mouseOver;
					areaDiv.onmouseout = mouseOut;
					
					var parentSpan = document.createElement(_spanTag);
					setStyleForElement(parentSpan,"parentSpan");
					
					var areaSpan = document.createElement(_spanTag);
					areaSpan.innerHTML = HighlightSearchText(areas[f].N); // the text for the suggested result...
					setStyleForElement(areaSpan, "displaySpan");

					var extraSpan = document.createElement(_spanTag);
					extraSpan.innerHTML = "&nbsp;" + _linkText + areas[f].LD;  // the text for the suggested result...
					setStyleForElement(extraSpan, "extraSpan");
						
					var summarySpan = document.createElement(_spanTag);
					setStyleForElement(summarySpan, "resultSpan");
					areaDiv.displaySpan = summarySpan;
					summarySpan.innerHTML = areas[f].R; 
					
					var hiddenIDSpan = document.createElement(_spanTag);
					hiddenIDSpan.innerHTML = areas[f].Id; // The id of the area.
					setStyleForElement(hiddenIDSpan, "uIDSpan");
					
					var hiddenDisplaySpan = document.createElement(_spanTag);
					hiddenDisplaySpan.innerHTML = areas[f].N; // The text to put in the input box. Unformatted
					setStyleForElement(hiddenDisplaySpan, "uDisplaySpan");
					
					var hiddenFullSpan = document.createElement(_spanTag);
					hiddenFullSpan.innerHTML = areas[f].N + _linkText + areas[f].LD; // The full area text.
					setStyleForElement(hiddenFullSpan, "uFullSpan");

					areaSpan.appendChild(extraSpan);
					parentSpan.appendChild(areaSpan);
					parentSpan.appendChild(summarySpan);
					parentSpan.appendChild(hiddenIDSpan);
					parentSpan.appendChild(hiddenDisplaySpan);
					parentSpan.appendChild(hiddenFullSpan);
					areaDiv.appendChild(parentSpan);

					elem.appendChild(areaDiv);
				}
			}
		}
	}
}

function HighlightSearchText(desc)
{	
	// Add a space to the description to find only occurance with the letters at the front of each word.
	// also search with non accented characters.
	var descTemp = ' ' + ReplaceSpecial(desc);
	
	var re = RegExp(' ' + ReplaceSpecial(_currentInputFieldValue), "i");	
	
	var index = descTemp.search(re);
	
	var replace = '';
	
	if (index > -1)
	{
		replace = desc.substring(index , index + _currentInputFieldValue.length);
	}
	
	return desc.replace(replace, '<span style="font-weight:bold">' + replace + '</span>');
}

// replaces accented vowels with unaccented vowels and ñ with n.
function ReplaceSpecial(str)
{
	var temp = str;

	// Regular expressions of character codes.
	var rExps = [/[\xC0-\xC5]/g, /[\xE0-\xE5]/g,
		/[\xC8-\xCB]/g, /[\xE8-\xEB]/g,
		/[\xCC-\xCF]/g, /[\xEC-\xEF]/g,
		/[\xD2-\xD8]/g, /[\xF2-\xF8]/g,
		/[\xD9-\xDC]/g, /[\xF9-\xFC]/g,
		/[\xD1]/g, /[\xF1]/g,
		/[\xC7]/g, /[\xE7]/g,
		/[\xDD]/g, /[\xFD]/g];

	var repChar = ['A','a','E','e','I','i','O','o','U','u','N','n','C','c','Y','y'];

	for (var i=0; i < rExps.length; i++)
	{
		temp = temp.replace(rExps[i],repChar[i]);
	}

	return temp;
}

// returns an XMLHttp object... gets it in an IE/Mozilla friendly way..
function getXMLHTTP()
{
	var xhttp = null;
	try
	{
		xhttp = new ActiveXObject("Msxml2.XMLHTTP")
	}
	catch (e)
	{
		try
		{
			xhttp = new ActiveXObject("Microsoft.XMLHTTP")
		} 
		catch (oc)
		{
			xhttp = null;
		}
	}
	if (!xhttp && typeof XMLHttpRequest != "undefined") 
	{
		xhttp = new XMLHttpRequest();
	}
	return xhttp;
}



// Select suggested entry...
function selectEntry(value)
{
	_inputField.value = value;
	_selectedValue = value;
}

function SelectAreaId(elem)
{
    try
    {
	    // select area with the id.
	    var areaId = findSpanValueForClass(elem, "uIDSpan");
	    var areaDescription = findSpanValueForClass(elem, "uFullSpan");
	    _inputField.title = areaDescription;
	    _changedElement = _inputField;
	
	    //ClearAreaDropDowns();
	    //ClearAreaGroup();
		if (document.getElementById("AJAX_numberOfResults")!=null)
		{
			xajax_XajaxChangePositionResultsForArea(14,'xajax_XajaxSelectSmartArea',areaId,_inputField.value);
		}else{
			if (document.getElementById("areasdefault")!=null){
				document.getElementById("areasdefault").selectedIndex=0;
			}else{
				if (document.getElementById("areaLevel_2")!=null) {
					document.getElementById("areaLevel_2").selectedIndex=0;
				}
				clearCombo('areaLevel_3');
				if (document.getElementById("areaGroups")!=null) {
					document.getElementById("areaGroups").selectedIndex=0;
				}
			}
			if ( document.getElementById("hiddenAreaId") != null ) {
				document.getElementById("hiddenAreaId").value=areaId;
			}
		}
	}
	catch (e)
	{
		alert("Error: " + e.message);
	}
}

function clearAreaSuggest()
{
      SetupPage()
}