function myScrollTo(container, element)
{
   
    var y = element.offsetTop;
   
    //container.scrollTop=y-(document.all?0:container.offsetTop);
    container.scrollTop = y-container.offsetHeight+element.offsetHeight;
    return element;
}

function showHideMap()
{
	$('map-hidder').style.display ='block'; 
	blindDiv('map-form',1);
}

function runSuggestionOnPaste()
{
	curentObject.provider.requestSuggestions(curentObject, true);
}


// function called when an global immoType checkBox is clicked. 
// It checked or discheck all immoSubType checkboxes children of the group
// (elementCheckbox, immoSubTypes checkBoxes divContainer  id)

function checkGoupImmotype(checkBoxGroup , divGroup)
{
	//checkBoxes = getElementsByClassName($(divGroup), 'input', 'checkbox')
	checkBoxes = $$('#'+ divGroup +' input.checkbox');
		
		if(checkBoxGroup.checked)
		{
			
			for(i = 0 ; i < checkBoxes.length ; i++)
			{
				checkBoxes[i].checked = 'checked';
			}
			
		}
		else
		{
			
			for(i = 0 ; i < checkBoxes.length ; i++)
			{
				checkBoxes[i].checked = false;
			}
		}
}

// function called when an immoSubType checkBox is clicked. 
// It check if all checkboxes from the group are checked or not 
// and autoChecked ou disChecked its gloabal group CheckBox (elementCheckbox, divContainer  id , global ElementCheckbox)

function checkImmoSubType(checkBox, divGroup , checkBoxGroup)
{
	
	//checkBoxes = getElementsByClassName($(divGroup), 'input', 'checkbox')
	checkBoxes = $$('#'+ divGroup +' input.checkbox');
	allGroupChecked = true;
	for(i = 0 ; i < checkBoxes.length ; i++)
	{
		if(!checkBoxes[i].checked)
		{
			allGroupChecked = false;
		}
		
	}
	if(allGroupChecked)
	{
		checkBoxGroup.checked = 'checked';
		checkBoxGroup.selected = true;
	}
	else
	{
		checkBoxGroup.checked = false;
		checkBoxGroup.selected = false;
	}
			
		
	

}

//Return an array of elements (rootElement,tagName searched, className searched)
/*
function getElementsByClassName(oElm, strTagName, oClassNames){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var arrRegExpClassNames = new Array();
	if(typeof oClassNames == "object"){
		for(var i=0; i<oClassNames.length; i++){
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
		}
	}
	else{
		arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
	}
	var oElement;
	var bMatchesAll;
	for(var j=0; j<arrElements.length; j++){
		oElement = arrElements[j];
		bMatchesAll = true;
		for(var k=0; k<arrRegExpClassNames.length; k++){
			if(!arrRegExpClassNames[k].test(oElement.className)){
				bMatchesAll = false;
				break;
			}
		}
		if(bMatchesAll){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}*/

//Hide immosubtype container 
function blindDiv(name,duration)
{ 	

	new Effect.toggle(name,'Blind', {duration:duration ,  afterFinish: changeIconToggler});
} 

function changeIconToggler(Effect)
{
	if(Effect.element.id && $(Effect.element.id + '-toggler'))
	{
		
		if($(Effect.element.id + '-toggler').getAttribute('state') == 'opened')
		{
			$(Effect.element.id + '-toggler').setAttribute('state','closed');
			$(Effect.element.id + '-toggler').style.background = 'url(/images_site/search/menu_plus.png) center left no-repeat';
			
			
		}
		else
		{
			$(Effect.element.id + '-toggler').setAttribute('state','opened');
			$(Effect.element.id + '-toggler').style.background = 'url(/images_site/search/menu_moins.png) center left no-repeat';
			
		}
		
	}
}

// Hide all immosubtype containers if they are all or no one checked.
function blindAllDiv()
{ 	
	containers = $$('div.ss-types');
	for(i=0 ; i < containers.length ; i++)
	{
		noneChecked = true;
		countChecked = 0;
		checkBoxes = $$('#'+ containers[i].id +' input.checkbox');
		for(j = 0 ; j < checkBoxes.length ; j++)
		{
			if(checkBoxes[j].checked)
			{
				countChecked ++;
				noneChecked = false;
			}	
		}
		if(noneChecked || countChecked == checkBoxes.length)
		{
			blindDiv(containers[i].id , 0);
		}
		
	}
} 

function callInProgress (xmlhttp) {  
	switch (xmlhttp.readyState) {  
		case 1: case 2: case 3:  
			return true;  
		break;  
		// Case 4 and 0  
		default:  
			return false;  
		break;  
	}  
} 


function reinitialyzeFields(elements)
{
	for(i = 0; i < elements.length ; i++)
	{
		switch(elements[i].type)
		{
			case 'checkbox':
				elements[i].checked = '';
			break;
			default:
				elements[i].value = '';
			break;
		}
	}
}

String.prototype.capitalize = function(){
	var splitedString = this.split('-');
	var newString = '';
	for(i = 0; i < splitedString.length ; i++)
	{
		if(i != 0)
		{
			newString += '-';
		}
		newString += splitedString[i].replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
	}
	return newString;
  };
  
function doSearch(form) {
	
	changeStateElementsInForm(form) 
	try {
	newUrl = '/action/search/results/q/'
	
		newUrl += gatherSearchParams()
	
	
	document.location = newUrl
	return false;
	} catch(e) {
		var msg = ''
		for(i in e) {
			msg += i + ':' + e[i] + '\n'		
		}
		
		return false
	}
}

function gatherSearchParams(excluded) {
	var form = document.forms.search
	var newUrl = ''
	var ig = new Array(); // immotype groups
	var it = new Array(); // immotype multiple
	var en = new Array(); // energy class multiple
	if(!excluded) excluded = []
	
	for (var i=0; i < form.elements.length; i++) {
		
		e = form.elements[i]
		skipThis = false
		for (j = 0; j < excluded.length ; j++) {
			
			if (e.name == excluded[j]) {
				skipThis = true
				break
			}
		}
		
		if(skipThis) {
			continue
		}
		
		switch(e.name) {
		
		case 'st':
			if(e.value)	newUrl += 'st/' + e.value + '/'
			break
		
		case 'location':
			if(e.value.indexOf(',') > 0) {
				escapedEntries = new Array
				entries = e.value.split(';')
				for (j = 0; j < entries.length ; j++) {
					entry = entries[j].split(',')
					escapedEntries[escapedEntries.length] = entry[0]+ ',' + entry[1]
				}
				newUrl += 'w/' + escapedEntries.join(';') + '/'
			}
			break
		
		case 'ro_toggle':
			var ro_toggled = e.checked
			break
			
		case 'ro':
			if(ro_toggled) {
				newUrl += 'ro/' + e.options[e.selectedIndex].value + '/'
			}
				break;
		
		case 'bg_from':
			if(e.value.replace(' ','') > 0 || form.elements.bg_to.value.replace(' ', '') > 0) newUrl += 'bg/' + e.value.replace(' ','') +','
			break

		case 'sf_from':
			if(e.value > 0 || form.elements.sf_to.value > 0) newUrl += 'sf/' + e.value +','
			break
			
		case 'rm_from':
			if(e.value > 0 || form.elements.rm_to.value > 0) newUrl += 'rm/' + e.value +','
			break
			
		case 'br_from':
			if(e.value > 0 || form.elements.br_to.value > 0) newUrl += 'br/' + e.value +','
			break

		case 'bg_to':
			if(e.value.replace(' ','') > 0) newUrl += e.value.replace(' ','') +'/'
			else if(form.elements.bg_from.value.replace(' ','') > 0) newUrl += '/'
			break  

		case 'sf_to':
			if(e.value > 0) newUrl += e.value + '/'
			else if(form.elements.sf_from.value > 0) newUrl += '/'
			break  

		case 'rm_to':
			if(e.value > 0) newUrl += e.value + '/'
			else if(form.elements.rm_from.value > 0) newUrl += '/'
			break 
			
		case 'br_to':
			if(e.value > 0) newUrl += e.value + '/'
			else if(form.elements.br_from.value > 0) newUrl += '/'
			break 
		
		case 'ig_h':
		case 'ig_f':
		case 'ig_r':
		case 'ig_g':
		case 'ig_e':
		case 'ig_o':
			
			if(e.checked) ig[ig.length] = '_' + e.value;
			break
			
		case 'it':
			if((e.checked && domainName == 'atofficelu') || (e.checked && e.getAttribute('group')== 'ig_o'))
			{
				it[it.length] =  e.value;
			}
			else if(e.checked && !$(e.getAttribute('group')).checked)  it[it.length] =  e.value;
			break		

		case 'tr':
			if(e.checked) newUrl += 'tr/' + e.value + '/'
			break
			
		case 'l':
		case 'h':
		case 'g':
		case 'c':
		case 'fu':
		case 'gc':
		case 'tb':
		case 'pc':
		case 'a':
		case 'rd':
		
			if(e.checked) newUrl += e.name+'/'
			break
		case 'build':
			if(e.value != '' && e.checked) newUrl += e.value+'/'
			break
		case 'ct':
		case 'cid':
		case 'km':
			if(e.value == '') break;
		case 'p':
		case 'r':
			newUrl += e.name+'/'+e.value+'/'
			break;
		case 'e':
			if(e.checked)
			{
				en[en.length] =  e.value;
			}
			break;
		}
		
	
	}
	
	// add immotype groups if any selected
	if(ig.length > 0) {
		newUrl += 'ig/' + ig.join(',') + '/';
	}
	// add multiple immotype if any selected
	if(it.length > 0) {
		newUrl += 'it/' + it.join(',') + '/';
	}
	// add multiple energy class if any selected
	if(en.length > 0) {
		newUrl += 'e/' + en.join(',') + '/';
	}
	return newUrl
}


function changeStateElementsInForm(form) {
	
	if($('spiner-search') != null && $('spiner-search').style.display == 'none')
	{
		$('spiner-search').style.display = 'block';
		$('grey-page').style.display = 'block';
	}
	else if($('spiner-search') != null)
	{
		$('spiner-search').style.display = 'none';
		$('grey-page').style.display = 'none';
	}
	for(i=0;i<form.elements.length;i++)
	{
		if(form.elements[i].getAttribute('disabled')==true || form.elements[i].getAttribute('disabled')=='disabled')
		{
			form.elements[i].removeAttribute('disabled');			
			if(form.elements[i].className=='bt-submit grayed') {
				form.elements[i].className='bt-submit';
			}
		}
		else
		{
			form.elements[i].setAttribute('disabled','disabled');
			if(form.elements[i].className=='bt-submit') {
				form.elements[i].className='bt-submit grayed';
			}
		}
	}	
}

document.onclick = function (oEvent)
{
	if(oLocalSug)
	{
		oLocalSug.hideSuggestions();
	}
}

initSearch = function () {	
	ajaxRequestLocation = '';
	timerAjaxRequetLocation = '';
	searchForm = document.forms.search;
	searchFormFields = searchForm.elements;
	locationField = [$('location')];
	caracteristiquesFields = [$('tb'),$('g'),$('gc'),$('c'),$('b'),$('a'),$('fu')];
	otherFields = [$('ro_toggle'),$('pc'),$('rd'),$('l'),$('h')];
	
	/*3e item du tab geo-> 1 = region, 2= departement (commune), 3= ville (localite) */
	DropDownListTxt = $("w");
	
	oLocalSug = new AutoSuggestControl(DropDownListTxt,  new Suggestions([],null,null));
	
	// Room Range Suggestions
	BRoomMin = [ ["1",""],["2",""],["3",""],["4",""],["5",""],["6",""] ];
	BRoomMax = [ ["1",""],["2",""],["3",""],["4",""],["5",""],["6",""] ];
	
	// Km Suggestions
	Km = [ ["",""],["1",""],["2",""],["3",""],["4",""],["5",""],["10",""],["15",""],["20",""]];
	
	
	switch(domainName)
	{
		
		case 'atofficelu':
			// Price Range Suggestions for Buy Transaction
			PriceMinBy = [ ["100 000",""],["200 000",""],["400 000",""],["600 000",""],["800 000",""],["1 000 000",""],["1 500 000",""] ];
			PriceMaxBy = [ ["100 000",""],["200 000",""],["400 000",""],["600 000",""],["800 000",""],["1 000 000",""],["1 500 000",""] ];
			
			// Price Range Suggestions for Rent Transaction
			PriceMinRt = [ ["1 000",""],["2 000",""],["3 000",""],["4 000",""],["5 000",""],["8 000",""],["10 000",""] ];
			PriceMaxRt = [ ["1 000",""],["2 000",""],["3 000",""],["4 000",""],["5 000",""],["8 000",""],["10 000",""] ];

			// Sup Range Suggestions
			SupMin = [ ["100",""],["500",""],["1 000",""],["2 000",""] ];
			SupMax = [ ["100",""],["500",""],["1 000",""],["2 000",""] ];
			
			
			
			// No superficies and room fields for the home page form
			if(!homePage)
			{
				oSupMin = new AutoSuggestControl( $("sf_from") ,  new Suggestions ( SupMin , $("sf_to") , 'max')); 
				oSupMax = new AutoSuggestControl( $("sf_to") ,  new Suggestions ( SupMax , $("sf_from") , 'min'));
				
			}
			
			
			
		break;
		case 'athomebe':
		case 'athomede':	
		case 'athomelorraine':		
		case 'athomealsace':
			
			// Price Range Suggestions for Buy Transaction
			PriceMinBy = [ ["100 000",""],["150 000",""],["200 000",""],["250 000",""],["300 000",""],["350 000",""],["400 000",""] ];
			PriceMaxBy = [ ["100 000",""],["150 000",""],["200 000",""],["250 000",""],["300 000",""],["350 000",""],["400 000",""] ];
			
			// Price Range Suggestions for Rent Transaction
			PriceMinRt = [ ["250",""],["400",""],["550",""],["600",""],["750",""],["900",""],["1 200",""] ];
			PriceMaxRt = [ ["250",""],["400",""],["550",""],["600",""],["750",""],["900",""],["1 200",""] ];

			// Sup Range Suggestions
			SupMin = [ ["15",""],["25",""],["50",""],["100",""],["150",""],["250",""] ];
			SupMax = [ ["15",""],["25",""],["50",""],["100",""],["150",""],["250",""] ];
			
			// Room Range Suggestions
			RoomMin = [ ["1",""],["2",""],["3",""],["4",""],["5",""],["6",""] ];
			RoomMax = [ ["1",""],["2",""],["3",""],["4",""],["5",""],["6",""] ];
			
			
			
			// No superficies and room fields for the home page form
			if(!homePage)
			{
				oSupMin = new AutoSuggestControl( $("sf_from") ,  new Suggestions ( SupMin , $("sf_to") , 'max')); 
				oSupMax = new AutoSuggestControl( $("sf_to") ,  new Suggestions ( SupMax , $("sf_from") , 'min'));
				oRoomMin = new AutoSuggestControl( $("rm_from") ,  new Suggestions ( RoomMin, $("rm_to") , 'max')); 
				oRoomMax = new AutoSuggestControl( $("rm_to"),  new Suggestions ( RoomMax, $("rm_from") , 'min'));
				oBRoomMin = new AutoSuggestControl( $("br_from") ,  new Suggestions ( BRoomMin, $("br_to") , 'max')); 
				oBRoomMax = new AutoSuggestControl( $("br_to"),  new Suggestions ( BRoomMax, $("br_from") , 'min'));
			}
			
		break;
	
		case 'athomelu':
		default:
			
			// Price Range Suggestions for Buy Transaction
			PriceMinBy = [ ["150 000",""],["250 000",""],["350 000",""],["450 000",""],["550 000",""],["650 000",""],["750 000",""] ];
			PriceMaxBy = [ ["150 000",""],["250 000",""],["350 000",""],["450 000",""],["550 000",""],["650 000",""],["750 000",""] ];
			
			// Price Range Suggestions for Rent Transaction
			PriceMinRt = [ ["400",""],["600",""],["800",""],["1 000",""],["1 300",""],["1 600",""],["2 000",""] ];
			PriceMaxRt = [ ["400",""],["600",""],["800",""],["1 000",""],["1 300",""],["1 600",""],["2 000",""] ];

			// Sup Range Suggestions
			SupMin = [ ["25",""],["50",""],["100",""],["150",""],["250",""] ];
			SupMax = [ ["25",""],["50",""],["100",""],["150",""],["250",""] ];
			
			
			// No superficies and room fields for the home page form
			if(!homePage)
			{
				oSupMin = new AutoSuggestControl( $("sf_from") ,  new Suggestions(SupMin , $("sf_to") , 'max')); 
				oSupMax = new AutoSuggestControl( $("sf_to") ,  new Suggestions(SupMax , $("sf_from") , 'min'));
				oBRoomMin = new AutoSuggestControl( $("br_from") ,  new Suggestions(BRoomMin, $("br_to") , 'max')); 
				oBRoomMax = new AutoSuggestControl( $("br_to"),  new Suggestions(BRoomMax, $("br_from") , 'min'));
			}
				
			
		break;
	}
	
	// Check Transaction field to create Price Range Suggestions
	var tr = document.forms.search.elements.tr;

	if(tr[0].checked)
	{
		oPriceMin = new AutoSuggestControl( $("bg_from") , new Suggestions(PriceMinBy , $("bg_to") , 'max')); 
		oPriceMax = new AutoSuggestControl( $("bg_to") , new Suggestions(PriceMaxBy , $("bg_from") , 'min'));
	}
	else
	{
		oPriceMin = new AutoSuggestControl( $("bg_from") , new Suggestions(PriceMinRt , $("bg_to") , 'max')); 
		oPriceMax = new AutoSuggestControl( $("bg_to") , new Suggestions(PriceMaxRt , $("bg_from") , 'min'));
	}
	
	oKm = new AutoSuggestControl( $("km") , new Suggestions(Km , null , null)); 
	changeStateElementsInForm(searchForm);

}

function Suggestions(suggestions,DependentBox,limit) {
	
    this.Suggestions = suggestions;
    this.DependentBox = DependentBox;
    this.limit = limit;
}
function launchAjaxRequestLocation (sTextboxValue,oAutoSuggestControl, bTypeAhead) {
	
	// first check if the user typed a reference
	if(sTextboxValue.match(/\d{6,}/)) {
		ajaxRequestReference = new Ajax.Request(
				
				'/search/load-offer-by-reference/'+sTextboxValue+'?tmp='+Math.random(),
				{
					method: 'post',
					onSuccess: function(transport, json) 
					{
					    if(json.url) {
					    	new Modalbox(json.title, json.info, json.close);
					    	document.location = json.url
					    } else {
					    	if(json.error) message = json.error
					    	else message = 'Unknown error'
					    	
					    	new Modalbox(json.title, message, json.close);
					    }
				    
					}
				}
			);
	}
	else {
	
		newUrl = gatherSearchParams(['location'])
		oAutoSuggestControl.textbox.className= "loading";
		ajaxRequestLocation = new Ajax.Request(
				
			'/search/autocomplete/'+sTextboxValue +'/'+ newUrl,
			{
				method: 'post',
				onSuccess: function(transport, json) 
				{
					
				    //provide suggestions to the control
				    oAutoSuggestControl.autosuggest(json, bTypeAhead);
				   
				    oAutoSuggestControl.textbox.className= "";
			    
				}
			}
		);
	}
}



Suggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                                                         bTypeAhead /*:boolean*/, fieldClick) {
	
	
	var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value;
    
    
    
    if(this.DependentBox == null && oAutoSuggestControl.textbox.id == "w")
    {
    	
    	if(sTextboxValue.length < 2)
    	{
    		
    		oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
    		window.clearTimeout(timerAjaxRequetLocation); 
    		ajaxRequestLocation = '';
    		return;
    	}
    	else 
    	{
    		if(ajaxRequestLocation != '' && callInProgress(ajaxRequestLocation.transport))
    		{
    			ajaxRequestLocation.transport.abort();
    			
    		}
    		ajaxRequestLocation = '';
    		window.clearTimeout(timerAjaxRequetLocation); 
    		value = sTextboxValue
    		autoSuggest = oAutoSuggestControl
    		typeAhead = bTypeAhead
    		timerAjaxRequetLocation = window.setTimeout(function () { launchAjaxRequestLocation (value, autoSuggest, typeAhead) }, 400);

    	}
    	
    }
    else
    {
    	
		for (var i=0; i < this.Suggestions.length; i++) 
		{   	
			buildArray = true;
		    if(this.DependentBox != null && this.DependentBox.value != '') 
		    {
			   	if(this.limit == 'min') {
			   		if(parseInt(this.Suggestions[i][0].replace(' ','')) < parseInt(this.DependentBox.value.replace(' ','')))
			   		{
			   			buildArray = false;
			   		} else { buildArray = true; }	
			  			
			   	} else if(this.limit == 'max') {
			   		if(parseInt(this.Suggestions[i][0].replace(' ','')) > parseInt(this.DependentBox.value.replace(' ','')))
			   		{
			   			buildArray = false;
			   		} else { buildArray=true; }	
			   	}
		    }
		    if(buildArray)
		    {
		    	
	    		if(sTextboxValue.length > 0 && fieldClick == undefined)
				{
					if (this.Suggestions[i][0].toLowerCase().replace(' ','').indexOf(sTextboxValue.replace(' ','').toLowerCase(),0) == 0 )
					{
						aSuggestions.push(this.Suggestions[i]);
					}
				}
				else
				{
					aSuggestions.push(this.Suggestions[i]);
				}
	    	}
	    	
		}
    	
		//provide suggestions to the control
	    oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
	    
    }
    
    
};

/**
 * An autosuggest textbox control.
 * @class
 * @scope public
 */
function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, 
                            oProvider /*:SuggestionProvider*/) {
    
    /**
     * The currently selected suggestions.
     * @scope private
     */   
    this.cur /*:int*/ = -1;

    /**
     * The dropdown list layer.
     * @scope private
     */
    this.layer = null;
    
    /**
     * Suggestion provider for the autosuggest feature.
     * @scope private.
     */
    this.provider /*:SuggestionProvider*/ = oProvider;
    
    /**
     * The textbox to capture.
     * @scope private
     */
    this.textbox /*:HTMLInputElement*/ = oTextbox;
    
    if(this.textbox.id == "w")
    {
    	this.textbox.clicked = false;
    }
    this.textbox.onmouseover = function()
    {
    	if(!this.focused)
    	{
    		this.style.border = "1px solid #7F7F7F";
    	}
    	
    }
    this.textbox.onmouseout = function()
    {
    	if(!this.focused)
    	{
    		this.style.border = "1px solid #c9c9c9";
    	}
    }
    /**
     * Array to prepare json code
     * @scope private
     */
    
    this.addedItems = new Array();
    
    this.Location = new Array();
    
    //initialize the control
    this.init();
    
}

/**
 * Autosuggests one or more suggestions for what the user has typed.
 * If no suggestions are passed in, then no autosuggest occurs.
 * @scope private
 * @param aSuggestions An array of suggestion strings.
 * @param bTypeAhead If the control should provide a type ahead suggestion.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/,
                                                     bTypeAhead /*:boolean*/) {
    
    //make sure there's at least one suggestion
    if (aSuggestions.length > 0) {
        /*
    	if (bTypeAhead) {
           this.typeAhead(aSuggestions[0][0]);
        }*/
        
        this.showSuggestions(aSuggestions);
    } else {
        this.hideSuggestions();
    }
};

/**
 * Creates the dropdown layer to display multiple suggestions.
 * @scope private
 */
AutoSuggestControl.prototype.createDropDown = function () {

    var oThis = this;

   
    //create the layer and assign styles
   
    
    this.layer = document.createElement("div");
    this.layer.appendChild(document.createElement("div"));
    
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    if(oThis.textbox.id == 'w') {
    	 this.layer.id = "suggestionsContainer";
    	 this.layer.className += " w";
    	 if(homePage)
    	 {
    		 this.layer.style.width = this.textbox.offsetWidth+"px"; 
    	 }
    }
	else if(oThis.textbox.id == 'km')
	{
		this.layer.style.width = "40px"; 
	}
    else
    this.layer.style.width = this.textbox.offsetWidth+"px"; 
    
   
    
    
    this.layer.onmouseover = function(oEvent)
    {
    	
    	this.onLayer = true;
    };
    this.layer.onmouseout = function(oEvent)
    {
    	this.onLayer = false;
    };


    //when the user clicks on the a suggestion, get the text (innerHTML)
    //and place it into a textboxben vi

    
    this.layer.firstChild.onmouseup = 
    this.layer.firstChild.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;
        
        if(oTarget.className!='label') 
        {
        	
	        if (oEvent.type == "mouseup" ) {
	        	
	        	 
				// If click is on span we have to get back to the parent div
	        	if(oTarget.tagName != "DIV")
				{
					oTarget= oTarget.parentNode;
				}	
				
	        	//If we are on localisation box we have to addItem to the selection and empty the field else we just complete the field
				if(oThis.textbox.id=='w')
				{
					
					oThis.addItem(oTarget);
					oThis.textbox.value="";
					
				}
				else
				{
					oThis.textbox.value = oTarget.lastChild.nodeValue;
					
				}
				
			
				oThis.textbox.scrolling = true;
				oThis.hideSuggestions();
				oThis.textbox.focus();
				if(oThis.textbox.id == 'km')
				{
					oThis.textbox.scrolling = false;
					oThis.textbox.blur();
				}
				
				
	            
	        } else if (oEvent.type == "mouseover") {
				if(oTarget.tagName == "DIV")
				{
						oThis.highlightSuggestion(oTarget);
				}
				else
				{
						oThis.highlightSuggestion(oTarget.parentNode);
				}
	        }
        }
    };
    
    document.body.appendChild(this.layer);
};

/**
 * Gets the left coordinate of the textbox.
 * @scope private
 * @return The left coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getLeft = function () /*:int*/ {

    var oNode = this.textbox;
    var iLeft = 0;
    
    while(oNode.tagName != "BODY") {
    	iLeft += oNode.offsetLeft;
    	oNode = oNode.offsetParent;        
    }
   
    
    return iLeft;
};

/**
 * Gets the top coordinate of the textbox.
 * @scope private
 * @return The top coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getTop = function () /*:int*/ {

    var oNode = this.textbox;
    var iTop = 0;
    
    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop;
};

/**
 * Handles three keydown events.
 * @scope private
 * @param oEvent The event object for the keydown event.
 */
AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {
	
	switch(oEvent.keyCode) {
		case 9:
		
			this.layer.onLayer = false;
			if(this.textbox.id == 'w') 
        	{
				if(this.cur > 0)
				{
					//User selected item on the list using arrows
					this.addItem(this.layer.firstChild.childNodes[this.cur]);
					this.textbox.value = '';
				}
				
			}
			else
			{
				if(this.cur >= 0)
				{
					this.textbox.value = this.layer.firstChild.childNodes[this.cur].lastChild.nodeValue;
				}
			}
			this.hideSuggestions();
			break;
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow 
        	
            this.nextSuggestion();
            break;
    }

};

/**
 * Handles three keypress events (Used for enter and escape button on IE)
 * @scope private
 * @param oEvent The event object for the keypress event.
 */

AutoSuggestControl.prototype.handleKeyPress = function (oEvent /*:Event*/) {
	
	switch(oEvent.keyCode) {
	
		
        case 13: //enter
       
        	if(this.textbox.id == 'w') 
        	{
        		
	        		if(this.cur>0)
	        		{
	        			//User selected item on the list using arrows
	        			this.addItem(this.layer.firstChild.childNodes[this.cur]);
	        			
	        		}
	        		
	        		if(this.layer.style.visibility == 'hidden' && this.textbox.value == '') { 
		        		 		
		        		doSearch(this.textbox.form);
	
		        	}
		        	else if(ajaxRequestLocation != '' && !callInProgress(ajaxRequestLocation.transport))
		        	{
		        		
		        		
		        		this.textbox.form.onsubmit=function() { this[this.currentFocusName].focus(); return false; };
		        		this.textbox.value='';
		       			this.hideSuggestions();
		       			
	        		}
		        	
        		
        	} 
        	else if(this.layer.style.visibility == 'hidden') 
        	{ 
        		doSearch(this.textbox.form);
	        }
	        else
	        {
        		if(this.cur >= 0)
        		{
        			this.textbox.value = this.layer.firstChild.childNodes[this.cur].lastChild.nodeValue;
        			
        		}
        		this.textbox.form.currentFocusName = this.textbox.name;
        		this.textbox.form.onsubmit=function() { this[this.currentFocusName].focus();return false};
        		this.hideSuggestions();
				if(this.textbox.id == 'km')
				{
					this.textbox.scrolling = false;
					this.textbox.blur();
				}
	        }
        		        	
        		
   			
            break;
        case 27: //escape
            this.hideSuggestions();
            break;
    }

};

/**
 * Handles keyup events.
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

    var iKeyCode = oEvent.keyCode;
    
    //for backspace (8) and delete (46), shows suggestions without typeahead
    if (iKeyCode == 8 || iKeyCode == 46) {
    	this.PreviousType = undefined;
        this.provider.requestSuggestions(this, false);
        
    //make sure not to interfere with 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.PreviousType = undefined;
        this.provider.requestSuggestions(this, true);
        
    }
};

/**
 * Hides the suggestion dropdown.
 * @scope private
 */
AutoSuggestControl.prototype.hideSuggestions = function () {
	this.layer.onLayer = false;
    this.layer.style.visibility = "hidden";
    this.layer.firstChild.innerHTML='';
    if(this.textbox.id=='w') {
    	this.cur=0;
    }
    else{
    	this.cur=-1;
    	
    }
    ajaxRequestLocation = '';
    
    
};

/**
 * Highlights the given node in the suggestions dropdown.
 * @scope private
 * @param oSuggestionNode The node representing a suggestion in the dropdown.
 */
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {
    
    for (var i=0; i < this.layer.firstChild.childNodes.length; i++) {
        var oNode = this.layer.firstChild.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "suggestion current";
            
            
            	
        } else if (oNode.className == "suggestion current") {
            oNode.className = "suggestion";
        }
        
    }
};

/**
 * Initializes the textbox with event handlers for
 * auto suggest functionality.
 * @scope private
 */
AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;
    this.textbox.setAttribute('autocomplete','off');
    //assign the onkeyup event handler
    this.textbox.onkeyup = function (oEvent) {
    	
        //check for the proper location of the event object
    	if (!oEvent) {
        	if(window.event) oEvent = window.event;
        	else oEvent=window.e;
        }    

        //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) {
        	if(window.event) oEvent = window.event;
        	else oEvent=window.e;
        }
        
        //call the handleKeyPress() method with the event object
        oThis.handleKeyDown(oEvent);
    };

    //assign onkeypress event handler (for enter and escape)
    this.textbox.onkeypress = function (oEvent) {
    	
    	
    	//check for the proper location of the event object
        if (!oEvent) {
        	if(window.event) oEvent = window.event;
        	else oEvent=window.e;
        }
        
        //call the handleKeyPress() method with the event object
        oThis.handleKeyPress(oEvent);
    };   
    

  	 //assign the onfocus event handler
  	this.textbox.onfocus = function (oEvent) {
  		
  		if(!this.scrolling)
  		{
	  		this.form.currentFocusName = this.name;
	  		
	  		if(this.value.length > 0)
	  		{
	  			oThis.selectRange(0,this.value.length);
	  		}
	  		
	  		if(this.id == "w" && !this.clicked)
	  		{
	  			this.clicked = true;
	  			this.value = '';
	  		}
	  		this.focused = true;
	  		this.style.border = "1px solid #C80000";
	
			oThis.provider.requestSuggestions(oThis, true,true);
  		}
  		else if(this.id == "w")
  		{
  			this.clicked = true;
  			this.focused = true;
  		}
  		
        
    }
  	this.textbox.onpaste = function(oEvent){
  		
  	
  		curentObject = oThis;
  		setTimeout('runSuggestionOnPaste()',5);
  		//oThis.PreviousType = undefined;
  		
  		//
  	}
  	
  

    //assign onblur event handler (hides suggestions)    
    this.textbox.onblur = function (e) {
    	
    	if(oThis.textbox.id == 'w' && oThis.textbox.value == '') {
    		
    		this.value = tradDefaultValueLocation;
    		this.clicked = false;
    		this.style.border = "1px solid #c9c9c9";
    		this.scrolling = false;
	 		/*id=oThis.textbox.value.match(/[0-9]{6,}/); 
			if(id!=null)
			{
		        //newUrl='http://'+athomeConfig.domainfull+'/action/bien/'+id+'?lang='+athomeConfig.lang;
		    	alert('Detail bien');
			}*/
    		
    	}
    	else if(!oThis.layer.onLayer)
        {
			
    		this.focused = false;
    		this.scrolling = false;
    		oThis.hideSuggestions();
    		this.style.border = "1px solid #c9c9c9";
			
			if(oThis.textbox.id == 'km')
			{
				checkContentRadius();
			}
        }
    	else
    	{
    		this.scrolling = true;
    		this.focus();
    	}

    };
    
    //create the suggestions dropdown
    this.createDropDown();
    
   
};

/**
 * Highlights the next suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
AutoSuggestControl.prototype.nextSuggestion = function () {
    var cSuggestionNodes = this.layer.firstChild.childNodes;
    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
        
        if(cSuggestionNodes[this.cur+1].className!='label')
        {
        	var oNode = cSuggestionNodes[++this.cur];
            this.highlightSuggestion(oNode);
            myScrollTo(this.layer, oNode);
            //this.textbox.value = oNode.lastChild.nodeValue;
            
        }
        else
        {
        	if(typeof(cSuggestionNodes[this.cur+2])!='undefined'){
            	var oNode = cSuggestionNodes[this.cur+2];
                this.cur=this.cur+2;
                this.highlightSuggestion(oNode);
                myScrollTo(this.layer, oNode);
                //this.textbox.value = oNode.lastChild.nodeValue;
	            
        	}
        }
    }
   
};

/**
 * Highlights the previous suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
AutoSuggestControl.prototype.previousSuggestion = function () {
	
    var cSuggestionNodes = this.layer.firstChild.childNodes;
    if (cSuggestionNodes.length > 0 && this.cur > 0) {
       if(cSuggestionNodes[this.cur-1].className!='label')
        {
    	   if(this.cur-1>=0) {
       			var oNode = cSuggestionNodes[--this.cur];
	            this.highlightSuggestion(oNode);
	            myScrollTo(this.layer, oNode);
	            //this.textbox.value = oNode.lastChild.nodeValue;
	            
    	   }
        }
        else
        {
        	if(this.cur-2>=0) {
	        	if(typeof(cSuggestionNodes[this.cur-2])!='undefined'){
	            	var oNode = cSuggestionNodes[this.cur-2];
	                this.cur=this.cur-2;
	                this.highlightSuggestion(oNode);
	                myScrollTo(this.layer, oNode);
	                //this.textbox.value = oNode.lastChild.nodeValue;
		           

	        	}                
        	}
        }
    }
};

/**
 * Selects a range of text in the textbox.
 * @scope public
 * @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*/) {
	
	
	 
	if(this.textbox.value.substr(iStart-1,1) == ' ')
    {
    	iStart++;
    } 
    
	
    //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.
 * @scope private
 * @param aSuggestions An array of suggestions for the control.
 */

AutoSuggestControl.prototype.addItem = function(oTarget) {
	
	var oTargetText = oTarget.lastChild.nodeValue;
	var oTargetValue = oTarget.getAttribute('value');
	var oTargetCode = oTarget.getAttribute('code');
	var oTargetCount = oTarget.firstChild.firstChild.nodeValue;
	if(oTargetValue=='') return false;

	oUl=$('dropDownListResultBox');
	
	if(!$(oTargetValue+'|'+oTargetCode))
	{
		oLi=document.createElement('li');
		oUl.appendChild(oLi);
		oLi.setAttribute("class",oTargetCode);
		oLi.setAttribute('value',oTargetValue);
		oLi.setAttribute("id",unescape(oTargetValue)+'|'+oTargetCode);
		
		if($("checkBox|" + oTargetValue+'|'+oTargetCode))
		{
			$("checkBox|" + oTargetValue+'|'+oTargetCode).checked = "checked";
			mapSelectBox($("checkBox|" + oTargetValue+'|'+oTargetCode),false);
			
		}
		oA=document.createElement('a');
		oA.href='javascript:;';
		oA.innerHTML='X';
		oA.onclick=function() { 
			
			this.parentNode.parentNode.removeChild(this.parentNode);
			
			if($("checkBox|" + this.parentNode.getAttribute('id')))
			{
				$("checkBox|" + this.parentNode.getAttribute('id')).checked = false;
				mapSelectBox($("checkBox|" + oTargetValue+'|'+oTargetCode),false);
			}
				
			oLocalSug.updateLocation();
		
			
			};
		oLi.appendChild(oA);
		
		oSpan=document.createElement('span');
		oSpan.innerHTML=oTargetCount;
		oSpan.setAttribute("class",'counter');
		oLi.appendChild(oSpan);
		
		oLi.appendChild(document.createTextNode(oTargetText));
		
		
	}
	this.updateLocation();
	
	
}


//Construct Location Search Array for ajax according to Ul list
AutoSuggestControl.prototype.updateLocation= function () {
	
	oUl = $('dropDownListResultBox');
	
	// add item to hidden input
	var location = document.forms.search.elements.location
	location.value = '';
	
	for(i=0;i<oUl.childNodes.length; i++)
	{
		if(location.value.length > 0) 
			location.value += ';'
		location.value += oUl.childNodes[i].getAttribute('class') + ',' + oUl.childNodes[i].getAttribute('value')
	}
};

AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) {
	
    var oDiv = null;
    
    this.layer.firstChild.innerHTML = "";  //clear contents of the layer    
    areaInCity = false;
    for (var i = 0 ; i < aSuggestions.length; i++) {
    	oDiv = document.createElement("div");
    	var neighborhood = '';
    	if(this.textbox.id=='w') {
    		var type=aSuggestions[i][2];
    		
	    	if(typeof(this.PreviousType) == 'undefined' || this.PreviousType!=type)
	    	{
	    		labelDiv = document.createElement("div");
	    		
    			this.PreviousType = type;		            
	            switch(type)
	            {
	            case 'r':
	            	labelDiv.innerHTML = tradRegion;
	            	labelDiv.className='label';
		            this.layer.firstChild.appendChild(labelDiv);
	            break;
	            case 'a':
	            	if(domainName != 'athomelu' && domainName != 'atofficelu')
		    		{
	            		if(!areaInCity)
	            		{
		            		areaInCity = true;
			    			labelDiv.innerHTML = tradCity;
			    			labelDiv.className='label';
				            this.layer.firstChild.appendChild(labelDiv);
	            		}
	            		this.PreviousType = 'c';
		    		}else 
		    		{
		    			labelDiv.innerHTML = tradArea;
		    			labelDiv.className='label';
			            this.layer.firstChild.appendChild(labelDiv);
		    		}
		        break;
	            case 'c':
	            	labelDiv.innerHTML = tradCity;
	            	labelDiv.className='label';
		            this.layer.firstChild.appendChild(labelDiv);
		        break;
	            }
	    			    		
	            
	            
	            
	    	}
	    	
	    	if(domainName != 'athomelu' && domainName != 'atofficelu' && type == 'a')
	    	{
	    		neighborhood = ' '+tradNeighborhood;
    		}
	    	
	    	oDiv.setAttribute('value',aSuggestions[i][0]);
	    	oDiv.setAttribute('code',aSuggestions[i][2]);	        
	        oSpan = document.createElement("span");
			oSpan.appendChild(document.createTextNode('('+aSuggestions[i][1]+')'));
			oDiv.appendChild(oSpan);
    	}
    	
       
		
    	oDiv.className = 'suggestion';
        oDiv.appendChild(document.createTextNode(aSuggestions[i][0]+neighborhood));
		
        this.layer.firstChild.appendChild(oDiv);
       
    }
    if(this.textbox.id=='w') 
    {
    	this.cur = -1;
    	this.nextSuggestion();
    }
	this.layer.style.left = this.getLeft() + 'px';
    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
    this.layer.style.visibility = "visible";

  

};

/**
 * Inserts a suggestion into the textbox, highlighting the 
 * suggested part of the text.
 * @scope private
 * @param sSuggestion The suggestion for the textbox.
 */
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality except for location
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        
    	var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
};


// misc function
function searchSetSort(value) {
	document.forms.search.st.value = value
	doSearch(document.forms.search)
}

function resizeImage(img, format) {
	switch(format) {
		case 'fp':
			var maxHeight = 130;
			var maxWidth = 173;
			break;
			
		case 'std':
			var maxHeight = 70;
			var maxWidth = 105;
			break;
			
		case 'gts':
			var maxHeight = 96;
			var maxWidth = 143;
			break;
			
		default:
			return;
			
	}
	
	var wScaleRatio;
	var hScaleRatio;

	img.style.display = 'block'
		
	wScaleRatio = img.width / maxWidth
	hScaleRatio = img.height / maxHeight
	
	//img.style.position = 'relative'
	
	var ratio = (wScaleRatio > hScaleRatio) ? wScaleRatio : hScaleRatio
	img.width = parseInt(img.width / ratio) // + 'px'
	// dunno why the hell I had to comment this to get resizing behaves as expected!
	// img.height = parseInt(img.height / ratio) // + 'px'
	
}




function showMap(region)
{

	//maps = getElementsByClassName($('map-box'), 'div', 'map-container')
	maps = $$('#map-box div.map-container');
	for(i=0 ; i < maps.length ; i++)
	{
		maps[i].style.display = "none";
	}
	if(region == false)
	{
		$('map-country').style.display = 'block';
		updateMapSuggestionList('','');
	}
	else
	{
		var idMap = 'map-'+region;
		$(idMap).style.display = 'block';
		if(region == 'Andere Länder')
		{
			updateMapSuggestionList('or',region);
		}
		else
		{
			updateMapSuggestionList('ra',region);
		}
	}
	

}

function updateMapSuggestionList(param,localisation)
{
	
	if(typeof(ajaxUpdaterMapSuggestion) != 'undefined' && callInProgress(ajaxUpdaterMapSuggestion.transport))
	{
		ajaxUpdaterMapSuggestion.transport.abort();
		
	}
	ajaxUpdaterMapSuggestion = '';
	
	urlAjax = '/search/places/';
	paramMapLocalisation = param;
	
	if(localisation != "Andere Länder")
	{
		if(param != '')
		{
			
			urlAjax += param + '/';
			
		}
		if(localisation != '')
		{
			urlAjax += encodeURIComponent(localisation)+'/';
		}
	}
	
	
	// adds search parameters
	urlAjax += gatherSearchParams(['location'])
	
	
	
	if(paramMapLocalisation == 'ra' || paramMapLocalisation == "or")
	{
		mapRegion = localisation;
	}
	else if(paramMapLocalisation == 'ac')
	{
		mapArea = localisation;
	}
	
	
	$('map-suggestion-listing').innerHTML = '';
	$('map-suggestion-listing').setAttribute('class','map-suggestion-listing-loading');
	
	ajaxUpdaterMapSuggestion = new Ajax.Request(
		
		urlAjax,
		{
			method: 'post',
			onSuccess: function(transport, json) 
			{
			 	createMapCheckboxList(json);
			}
		}
	);	

	
	
}
function createMapCheckboxList(aSuggestions)
{
	$('map-suggestion-listing').innerHTML = '';
	$('map-general-selection').innerHTML = '';
	$('map-general-selection').style.height = '0px';
	$('map-suggestion-listing').style.height = '330px';
	
	
	
	//Generate the map parent location suggestion
	allBoxSelected = false;
	oSpanParent = false;
	oCheckBoxParent = false
	
	if(aSuggestions.length > 0 && paramMapLocalisation != "")
	{
		
		// Checkbox select parent location
		oP = document.createElement("p");
		oSpan = document.createElement("span");
		oSpan.setAttribute('class','counter');
		oTextNode = document.createTextNode('');
		oSpan.appendChild(oTextNode);
		oSpanParent = oSpan;
		oP.appendChild(oSpan);
		
		oLabel = document.createElement("label");
		oCheckBox = document.createElement("input");
		oCheckBoxParent = oCheckBox;
		oCheckBox.setAttribute('type','checkbox');
		oCheckBox.setAttribute('class', 'checkBox');
		oCheckBox.setAttribute('counter','');
		oLabel.appendChild(oCheckBox);
		
		
		// Checkbox select all for multiselection search map
		oPAll = document.createElement("p");
		oLabelAll = document.createElement("label");
		oCheckBoxAll = document.createElement("input");
		oCheckBoxAll.setAttribute('type','checkbox');
		oCheckBoxAll.setAttribute('class', 'checkBox');
		oCheckBoxAll.setAttribute('id', 'SelectAllMapBox');
		oLabelAll.appendChild(oCheckBoxAll);
		oTextNodeAll = document.createTextNode(' ' + tradSelectAll);
		oLabelAll.appendChild(oTextNodeAll);
		oPAll.appendChild(oLabelAll);
		
		oCheckBoxAll.onclick = function()
		{
			mapSelectAllBoxes();
		}
		
		
		switch(paramMapLocalisation)
		{
			case 'ra':
				oCheckBox.setAttribute('id','checkBox|' +  mapRegion + '|r')
				oCheckBox.setAttribute('value', mapRegion);
				oCheckBox.setAttribute('code', 'r');
				oCheckBox.onclick = function()
				{
					mapSelectBoxParent(this)
				}
				
				
				oTextNode = document.createTextNode(' ' + tradAllRegion);
				
				oPor = document.createElement("p");
				oPor.setAttribute('id','mapChoiseMessage');
				oTextNodeOr = document.createTextNode(tradOrSelectArea);
				oPor.appendChild(oTextNodeOr);
				
				
				
				break;
			case 'ac':
				oCheckBox.setAttribute('id','checkBox|' +  mapArea + '|a')
				oCheckBox.setAttribute('value', mapArea);
				oCheckBox.setAttribute('code', 'a');
				oCheckBox.onclick = function()
				{
					mapSelectBoxParent(this)
				}
				
				
				oTextNode = document.createTextNode(' ' + tradAllArea);
				
				oPor = document.createElement("p");
				oPor.setAttribute('id','mapChoiseMessage');
				oTextNodeOr = document.createTextNode(tradOrSelectCity);
				oPor.appendChild(oTextNodeOr);
				
				
				
				break;
				
		}
		
		oLabel.appendChild(oTextNode);
		oP.appendChild(oLabel);
		
		
		
		$('map-general-selection').appendChild(oP);
		$('map-general-selection').appendChild(oPor);
		$('map-general-selection').appendChild(oPAll);
		$('map-suggestion-listing').style.height = '240px';
		$('map-general-selection').style.height = '90px';
		
		
		
		
		
	}	
	
	//Generate the map list suggestions
	oneBoxSelected = false;
	allBoxSelected = true;
	generalCounter = 0;
	
	for (var i = 0 ; i < aSuggestions.length; i++) 
	{
		
		
		if(paramMapLocalisation == "" || (paramMapLocalisation == "ra" && aSuggestions[i][2] == "a") || (paramMapLocalisation == "ac" && aSuggestions[i][2] == "c") || (paramMapLocalisation == "or" && aSuggestions[i][2] == "r" && aSuggestions[i][0] != "Saarland" && aSuggestions[i][0] != "Rheinland-Pfalz"))
		{
			generalCounter += aSuggestions[i][1];
			oP = document.createElement("p");
			
			oSpan = document.createElement("span");
			oSpan.setAttribute('class','counter');
			oTextNode = document.createTextNode('('+aSuggestions[i][1]+')');
			oSpan.appendChild(oTextNode);
			oP.appendChild(oSpan);
			
			oLabel = document.createElement("label");
			oCheckBox = document.createElement("input");
			oCheckBox.setAttribute('type','checkbox');
			oCheckBox.setAttribute('id','checkBox|' + aSuggestions[i][0] + '|' +  aSuggestions[i][2])
			oCheckBox.setAttribute('value',aSuggestions[i][0]);
			oCheckBox.setAttribute('code',aSuggestions[i][2]);
			oCheckBox.setAttribute('class','checkBox');
			oCheckBox.setAttribute('counter',aSuggestions[i][1]);
			oLabel.appendChild(oCheckBox);
			if( $(aSuggestions[i][0] + '|' + aSuggestions[i][2]))
			{
				oCheckBox.setAttribute('checked','checked');
				oneBoxSelected = true;
			}
			else
			{
				allBoxSelected = false;
			}
			oCheckBox.onclick = function()
			{
				mapSelectBox(this,true)
			}
			neighborhood = '';
			
			/*if(domainName != 'athomelu' && domainName != 'atofficelu' && type == 'a')
			{
				neighborhood = ' '+tradNeighborhood;
			}*/
			
			oTextNode = document.createTextNode(' '+aSuggestions[i][0]+neighborhood);
			oLabel.appendChild(oTextNode);
			
			oP.appendChild(oLabel);
			
			$('map-suggestion-listing').appendChild(oP);
		}
		
	}
	
	// Set parent location counter
	if(oSpanParent && oCheckBoxParent)
	{
		oSpanParent.innerHTML = '(' + generalCounter + ')';
		oCheckBoxParent.setAttribute('counter',generalCounter);
	}
	
	// Check parent location box if no children selected and we are not on a global region map
	if(oCheckBoxParent && !oneBoxSelected && paramMapLocalisation == "ac")
	{
		oCheckBoxParent.setAttribute("checked", "checked");
		if(!$(oCheckBoxParent.getAttribute('value') + '|' + oCheckBoxParent.getAttribute('code')))
		{
			mapAddItem(oCheckBoxParent);
		}
	}
	else if(oCheckBoxParent && $(oCheckBoxParent.getAttribute('value') + '|' + oCheckBoxParent.getAttribute('code')))
	{
		mapAddItem(oCheckBoxParent);
	}

	// check selectall box if all children locations are selected
	if(allBoxSelected && $('SelectAllMapBox'))
	{
		$('SelectAllMapBox').setAttribute('checked','checked');
	}
	
	// set the title and back link for the map suggestion listing	
	if(paramMapLocalisation == "ac")
	{
		$('suggestion-map-listing-title').innerHTML = mapArea;
		$('back-map').setAttribute('onclick' , "showMap('" + mapRegion + "')") ;

	}
	else if(paramMapLocalisation == "ra" || paramMapLocalisation == "or")
	{
		$('suggestion-map-listing-title').innerHTML = mapRegion;
		if(domainName == "athomede" && mapRegion != "Andere Länder" && mapRegion != "Saarland" && mapRegion != "Rheinland-Pfalz")
		{
			$('back-map').setAttribute('onclick' , "showMap('Andere Länder')") ;
		}
		else
		{
			$('back-map').setAttribute('onclick' , "showMap(false)") ;
		}
	}
	else
	{
		$('back-map').setAttribute('onclick' , "blindDiv('map-form',1)") ;

		$('suggestion-map-listing-title').innerHTML = tradPays;
	}
	
	// Remove loading appearence
	$('map-suggestion-listing').setAttribute('class','');
}

function mapSelectAllBoxes()
{
	
	//checkBoxes = getElementsByClassName($('map-suggestion-listing'), 'input', 'checkBox');
	checkBoxes = $$('#map-suggestion-listing input.checkBox');
	
	if($('SelectAllMapBox').checked)
	{
		for(a = 0 ; a < checkBoxes.length ; a++)
		{
			if(!checkBoxes[a].checked)
			{
				checkBoxes[a].checked = 'checked';
				mapAddItem(checkBoxes[a]);
			}
		}
		
	}
	else
	{
		
		for(a = 0 ; a < checkBoxes.length ; a++)
		{
			if(checkBoxes[a].checked)
			{
				checkBoxes[a].checked = false;
				mapAddItem(checkBoxes[a]);
			}
		}
	}
	
	// Unselect the parent location
	if(oCheckBoxParent && oCheckBoxParent.checked == true)
	{
		oCheckBoxParent.checked = false;
		oCheckBoxParent.onclick();
	}
	
}

function  mapSelectBoxParent(checkBox)
{	
	mapAddItem(checkBox);
	if(checkBox.checked)
	{
		$('SelectAllMapBox').checked =false;
		//checkBoxes = getElementsByClassName($('map-suggestion-listing'), 'input', 'checkBox');
		checkBoxes = $$('#map-suggestion-listing input.checkBox');
		
		for(a = 0 ; a < checkBoxes.length ; a++)
		{
			if(checkBoxes[a].checked)
			{
				checkBoxes[a].checked = false;
				mapAddItem(checkBoxes[a]);
			}
		}
			
		
	}
}

function  mapSelectBox(checkBox,addItem)
{
	
	//checkBoxes = getElementsByClassName($('map-suggestion-listing'), 'input', 'checkBox');
	checkBoxes = $$('#map-suggestion-listing input.checkBox');
	allGroupChecked = true;
	
	for(i = 0 ; i < checkBoxes.length ; i++)
	{
		if(!checkBoxes[i].checked)
		{
			allGroupChecked = false;
		}
		
	}
	if($('SelectAllMapBox') && allGroupChecked)
	{
		$('SelectAllMapBox').checked = 'checked';
	
	}
	else if($('SelectAllMapBox'))
	{
		$('SelectAllMapBox').checked = false;
		
	}
	
	// Unselect the parent location
	if(oCheckBoxParent && oCheckBoxParent.checked == true)
	{
		oCheckBoxParent.checked = false;
		oCheckBoxParent.onclick();
	}
	
	
	if(addItem)
	{
		mapAddItem(checkBox);
	}

}

function mapAddItem(checkBox)
{
	
	oUl = $('dropDownListResultBox');
	
	if(checkBox.checked && !$(checkBox.value+'|'+ checkBox.getAttribute('code')))
	{
		oLi=document.createElement('li');
		oUl.appendChild(oLi);
		oLi.setAttribute("class",checkBox.getAttribute('code'));
		oLi.setAttribute('value',checkBox.value);
		oLi.setAttribute("id",checkBox.value+'|'+checkBox.getAttribute('code'));
		
		oA=document.createElement('a');
		oA.href='javascript:;';
		oA.innerHTML='X';
		oA.onclick=function() { 
			
			this.parentNode.parentNode.removeChild(this.parentNode);
			oLocalSug.updateLocation();
			
			if($("checkBox|" + this.parentNode.getAttribute('id')))
			{
				
				$("checkBox|" + this.parentNode.getAttribute('id')).checked = false;
				mapSelectBox($("checkBox|" + this.parentNode.getAttribute('id')),true);
				
			}
			
		};
		oLi.appendChild(oA);
		
		oSpan=document.createElement('span');
		oSpan.innerHTML = '('+checkBox.getAttribute('counter')+')';
		oSpan.setAttribute("class",'counter');
		oLi.appendChild(oSpan);
		
		oLi.appendChild(document.createTextNode(checkBox.value));
	}
	else if($(checkBox.value+'|'+ checkBox.getAttribute('code')))
	{
		
		oUl.removeChild($(checkBox.value+'|'+ checkBox.getAttribute('code')));
	}
		
	
	oLocalSug.updateLocation();
}

function checkEnergyClass()
{
	//checkBoxes = getElementsByClassName($('block-e'), 'input', 'checkBox');
	checkBoxes = $$('#block-e input.checkBox');
	oneChecked = false;
	
	for(i = 0 ; i < checkBoxes.length ; i++)
	{
		if(checkBoxes[i].checked)
		{
			oneChecked = true;
		}
		
	}
	if(oneChecked)
	{
		$('e-toggler').checked = 'checked';
	
	}
	else
	{
		$('e-toggler').checked = false;
		
	}
}

function checkContentRadius()
{
	if($('km').value != '' )
	{
		$('kmText').innerHTML = $('km').value;
		$('kmFieldContainer').style.display = 'none';
		$('kmTextContainer').style.display = 'block';
	}
	
}

function deleteRadius()
{
	
		$('kmText').innerHTML = '';
		$('km').value = '';
		$('kmTextContainer').style.display = 'none';
		$('kmFieldContainer').style.display = 'block';
		
	
	
}

function cancelLink(link)
{
	
	if(link.cancel == 1)
	{
		return false;
	}
	else
	{
		return true;
	}
}



