function searchFormValidation()
{

	$('lang').disabled = true;
	$('editableFacet').disabled = true;
	$('sort').disabled = true;
	$('MainSearchFieldType').disabled = true;
	if ($('dateTypeSelectbox')) { $('dateTypeSelectbox').disabled = true; }
	if ($('rnax_hasTaxonConcept') && $('rnax_hasTaxonConcept').getValue() == '') { $('rnax_hasTaxonConcept').disabled = true; }
	if ($('freetext') && $('freetext').getValue() == '') { $('freetext').disabled = true; }
	
	var formContent = $('spFacetSearchForm').serialize();
	$('lang').disabled = false;
	$('editableFacet').disabled = false;
	$('sort').disabled = false;
	$('MainSearchFieldType').disabled = false;
	if ($('dateTypeSelectbox')) { $('dateTypeSelectbox').disabled = false; }
	if ($('rnax_hasTaxonConcept')) { $('rnax_hasTaxonConcept').disabled = false; }
	if ($('freetext')) { $('freetext').disabled = false; }

	if (formContent == '')
	{
		if ($('lang').getValue() == 'nl')
		{
			alert('het zoekveld is leeg');
		} 
		else
		{
			alert('the searchfield is empty');
		}
		
		return false;
	}
	else
	{
		return true
	}
	
}

function onSubmitFacetSearch()
{
	$('spFacetSearchForm').action = "/collections/sterna-birdwatchers-portal/sternafacetsearchresults";
	return true;
}

function clearEditableFacet()
{
	$('editableFacet').value = "-";
	return true;
}

function submitSearchForm(destination)
{
	switch (destination)
	{
		case 'self':
			clearEditableFacet();
			$('spFacetSearchForm').action = "/collections/sterna-birdwatchers-portal/search-for-content";
			break;
		default:
			break;
	}
}


// *********************************************************************
//
// datepicker control for selecting input type
//
// *********************************************************************

var dateFieldControl = Class.create();

dateFieldControl.prototype = {
	targetElement: undefined,
	selectBoxId: undefined,
	interfaceLanguage: "en",
	enabled: false,

	initialize: function(_selectBoxId, _targetElement, _interfaceLanguage)
	{
		if ($(_targetElement)) this.targetElement = _targetElement;
		if ($(_selectBoxId)) this.selectBoxId = _selectBoxId;
		this.interfaceLanguage = (_interfaceLanguage == "nl") ? "nl" : "en";
		this.enabled = ($(_targetElement) && $(_selectBoxId)) ? true : false;
		this.onChangeDatePickerSelect();
	},

	onChangeDatePickerSelect: function()
	{
		if (this.enabled)
		{
			$('dateField1Value').disable();
			$('dateField2Value').disable();
			$('dateField3Value').disable();
			$('dateField4Value').disable();
			
			switch ($(this.selectBoxId).getValue())
			{
				case "between":
					this.showDatePicker('option1');
					Calendar.setup({ dateField: 'dateField1Value', triggerElement: '1_dateFromBtn', guiLanguage: this.interfaceLanguage });
					Calendar.setup({ dateField: 'dateField2Value', triggerElement: '1_dateToBtn', guiLanguage: this.interfaceLanguage });
					$('dateField1Value').enable();
					$('dateField2Value').enable();
					break;
				case "from":
					this.showDatePicker('option2');
					Calendar.setup({ dateField: 'dateField3Value', triggerElement: '2_dateFromBtn', guiLanguage: this.interfaceLanguage });
					$('dateField3Value').enable();
					break;
				case "to":
					this.showDatePicker('option3');
					Calendar.setup({ dateField: 'dateField4Value', triggerElement: '3_dateToBtn', guiLanguage: this.interfaceLanguage });
					$('dateField4Value').enable();
					break;
				default:

					break;
			}
		}
	},

	showDatePicker: function(datePicker)
	{
		// hide all options
		if ($('option1') && $('option2') && $('option3') && (datePicker == 'option1' || datePicker == 'option2' || datePicker == 'option3') && this.enabled)
		{
			$('option1').hide();
			$('option2').hide();
			$('option3').hide();

			// show the selected one
			if ($(datePicker))
				$(datePicker).show();
			else
				$('option1').show();

			this.setCalendarBtnEvents();
		} else
		{
			this.enabled = false;
		}
	},


	setCalendarBtnEvents: function()
	{
		if (this.enabled)
		{
			$$('.calendarBtn').each(function(box)
			{
				Event.observe(box.id, 'mouseover', function(event)
				{
					$(box.id).src = '/images/calendar/calendar_icon_on.gif';
					document.body.style.cursor = 'pointer';
				});

				Event.observe(box.id, 'mouseout', function(event)
				{
					$(box.id).src = '/images/calendar/calendar_icon_off.gif';
					document.body.style.cursor = 'default';
				});
			});
		}
	}
}

var datePickerButtonControl = Class.create();

datePickerButtonControl.prototype = {
	initialize: function(){},
	
	onmouseover: function(img){
		alert('aan');
		img.src = '/images/calendar/calendar_icon_on.gif';
	},
	
	onmouseout: function(img){
		img.src = '/images/calendar/calendar_icon_off.gif';
	}
}


// *********************************************************************
//
// Select Tree Facet control for Facet selectboxes in a tree
//
// *********************************************************************

var selectTreeControl = Class.create();

selectTreeControl.prototype = {
	onChangeScript: undefined,
	initialize: function() { },
	toggleBrancheStatus: function(brancheId)
	{
		if ($('a_' + brancheId))
		{
			if ($('a_' + brancheId).className == 'min')
			{
				$('a_' + brancheId).removeClassName('min');
				$('a_' + brancheId).addClassName('plus');
				$('li_' + brancheId).removeClassName('open');
				$('li_' + brancheId).addClassName('closed');
				$('ul_' + brancheId).hide();
			}
			else
			{
				$('a_' + brancheId).removeClassName('plus');
				$('a_' + brancheId).addClassName('min');
				$('li_' + brancheId).removeClassName('closed');
				$('li_' + brancheId).addClassName('open');
				$('ul_' + brancheId).show();
			}
		}
	},

	selectTreeNode: function(nodeId, nodeType, obj)
	{
		if (obj.tagName != 'INPUT') { $('input_' + nodeId).checked = ($('input_' + nodeId).checked) ? false : true; }
		if ($('ul_' + nodeId))
		{
			var category = $('ul_' + nodeId);
			var inputs = $A(category.getElementsByTagName('INPUT'));
			inputs.each(function(input) { input.checked = ($('input_' + nodeId).checked) ? true : false; })
		}

		if (this.synchronizeRootCheckBox() && this.synchronizeCategoryCheckBox(nodeId, nodeType))
		{
			this.onChange();
		}
	},

	onChange: function()
	{
		if (this.onChangeScript != '' || this.onChangeScript != undefined || this.onChangeScript != null)
		{
			eval(this.onChangeScript);
		}
	},

	synchronizeRootCheckBox: function()
	{
		if ($('input_it_root'))
		{
			var completeSelection = true;
			var category = $('ul_it_root');
			var inputs = $A(category.getElementsByTagName('INPUT'));
			inputs.each(function(input)
			{
				if (!(input.checked))
				{
					completeSelection = false;
				}
			})
			$('input_it_root').checked = completeSelection;
		}
		return true;
	},

	synchronizeCategoryCheckBox: function(nodeId, nodeType)
	{
		var ParentNodes = $('input_' + nodeId).ancestors();

		ParentNodes.each(function(element)
		{
			if (element.tagName == "UL")
			{
				var completeSelection = true;
				var category = $('ul_' + element.id.substring(3));
				if (category != null)
				{
					var inputs = $A(category.getElementsByTagName('INPUT'));
					inputs.each(function(input)
					{
						if (!(input.checked))
						{
							completeSelection = false;
						}
					})
					$('input_' + element.id.substring(3)).checked = completeSelection;
				}
			}
		})
		return true;
	}
}



// *********************************************************************
//
// Facet Select Box control for Facet selectboxes functionality
//
// *********************************************************************

var selectBoxControl = Class.create();

selectBoxControl.prototype = {
	selectBoxId: undefined,
	selectListId: undefined,
	selectBox: null,
	selectList: null,
	
	initialize: function(_selectId)
	{
		if ($(_selectId) && $(_selectId).tagName == "SELECT")
		{
			this.selectBoxId = _selectId;
			this.selectBox = $(_selectId);
		} 
		else if ($(_selectId) && $(_selectId).tagName == "DIV")
		{
			this.selectListId = _selectId;
			this.selectList = $(_selectId);
			this.selectListInputs = $A(this.selectList.getElementsByTagName('INPUT'));
		}		
	},
	
	select: function(id)
	{
		if (id == 'all') this.update('SELECT');
	},
	
	deselect: function(id)
	{	
		if (id == 'all') this.update('DESELECT');
	},
	
	update: function(action)
	{
		if (this.selectBox)
		{
			for (var i=0; i<this.selectBox.options.length; i++) 
			{
				this.selectBox.options[i].selected = (action=='SELECT')? true: false;
			}
		} else if (this.selectList)
		{
			for (var i=0; i <= this.selectListInputs.length-1; i++)
			{
				this.selectListInputs[i].checked = (action=='SELECT')? true: false;
			}
		}
	}		
}



// *********************************************************************
//
// Toggle FacetInterface Select Box control for selecting interface
//
// *********************************************************************

var toggleFacetInterface = Class.create();

toggleFacetInterface.prototype = {
	selectBox:null,
	selectBoxArray:null,
	
	initialize: function(_selectBoxId)
	{
		if ($(_selectBoxId))
		{
			this.selectBox = $(_selectBoxId);
			this.selectBoxArray = $A(this.selectBox.getElementsByTagName('OPTION'));

			if (this.selectBoxArray.size() >= 2)
			{ 
				this.selectBox.observe('change', this.onChangeSelect.bind(this));
				this.onChangeSelect();
			} else if (this.selectBoxArray.size() <= 1)
			{ 
				this.hideInterface(_selectBoxId);
				this.onChangeSelect();
			} 
		}	
	},
	
	onChangeSelect: function ()
	{
		this.selectBoxArray.each(function(s)
		{  
			$(s.value).disabled = true; 
			$(s.value).hide();
		});
		if ($($F(this.selectBox))) 
		{
			this.showInterface($F(this.selectBox));
		}
	},
	
	showInterface: function(_id)
	{
		if($(_id)) $(_id).show();
		if($(_id)) $(_id).disabled = false;
		
	},
	
	hideInterface: function(_id)
	{
		if($(_id)) $(_id).disabled = 'true';
		if($(_id)) $(_id).hide();
	}
}


// *********************************************************************
//
// automaticly refresh the form after changes
//
// *********************************************************************

var formReloaderClass = Class.create();

formReloaderClass.prototype = {
	formId: undefined,
	
	initialize: function(_formId)
	{
		if($(_formId) && $(_formId).tagName == 'FORM')	this.formId = _formId;
	},
	
	setListener: function(elementID)
	{
		if ($(elementID))
			$(elementID).observe('change', this.startCountForReload);
	},
	
	startCountForReload: function()
	{
		var timer = setTimeout("reloadFacetSearchForm('"+this.formId+"')",250);
	},
	
	reloadForm: function()
	{
		var postData = Form.serialize($(this.formId));
		var baseUrl = '';
		var currentUrl = top.window.location.href;
		
		if ( currentUrl.indexOf('?',0) != -1)
			baseUrl = currentUrl.substr(0, currentUrl.indexOf('?'));
		else
			baseUrl = top.window.location.href;
			
		top.window.location.href = baseUrl+'?'+postData;
	}
	
}
// deze functie buiten de class omdat deze ook via de timer aanroepen moet kunnen worden
function reloadFacetSearchForm(lang)
{
	var postData = Form.serialize($('spFacetSearchForm'));
	var baseUrl = '';
	var currentUrl = top.window.location.href;

	if ( currentUrl.indexOf('?',0) != -1)
		baseUrl = currentUrl.substr(0, currentUrl.indexOf('?'));
	else
		baseUrl = top.window.location.href;

	top.window.location.href = baseUrl+'?'+postData;
}



// *********************************************************************
//
// Google Earth Interface for rna toolset
//
// *********************************************************************

var mapsInterface = Class.create();

mapsInterface.prototype = {
	map: "",
	places: [],
	markers: [],
	polyShape: "",
	polyShapeBorder: "",
	polygonMode: "",
	polygonDepth: "20",
	polyPoints: [],
	polySquare: [],
	areaSize: 0,
	marker: "",
	geocoder: null,

	fillColor: "#fff",
	lineColor: "#ff0000",
	opacity: .5,
	lineWeight: 1,
	newIcon: "",
	oldIcon: "",
	onChangeScript: undefined,

	initialize: function(mapsElementId)
	{
		if (GBrowserIsCompatible() && $(mapsElementId))
		{
			this.map = new GMap2(document.getElementById(mapsElementId));
			this.map.addControl(new GLargeMapControl());
			this.map.addControl(new GMapTypeControl());
			this.geocoder = new GClientGeocoder();
			GEvent.addListener(this.map, 'click', this.mapClick.bind(this));

			if ($('locationMapGuiLat') && $('locationMapGuiLng') && $('locationMapGuiZoomLvl'))
			{
				var viewPortLat = parseFloat($('locationMapGuiLat').getValue());
				var viewPortLng = parseFloat($('locationMapGuiLng').getValue());
				var viewPortZm = parseInt($('locationMapGuiZoomLvl').getValue());
				if (viewPortLat != NaN && viewPortLng != NaN && viewPortZm) { this.map.setCenter(new GLatLng(viewPortLat, viewPortLng), viewPortZm) }
				else { this.map.setCenter(new GLatLng(49.29074092493992, 52.03125), 2) }
			}

			this.oldIcon = new GIcon(false, "/images/oldPoint.gif");
			this.oldIcon.iconSize = new GSize(6, 6);
			this.oldIcon.iconAnchor = new GPoint(3, 3);

			this.newIcon = new GIcon(false, "/images/oldPoint.gif");
			this.newIcon.iconSize = new GSize(6, 6);
			this.newIcon.iconAnchor = new GPoint(3, 3);

			if (this.setPredefinedSelection()) { this.drawCoordinates() }
		}
	},

	mapClick: function(marker, clickedPoint)
	{
		this.polygonMode = true;
		if ((clickedPoint != undefined && marker == null) || (marker == this.oldMarker) || (marker == this.newMarker))
		{

			if (clickedPoint != undefined && marker == null)
			{
				this.removeOverlays('ALL');
				this.oldMarker = marker;
				this.polyPoints.push(clickedPoint);
				this.polyPoints.splice(0, (this.polyPoints.length - 2));
			}
			else
			{
				if (marker == this.oldMarker) { this.removeOverlays('ALL') }
				else if (marker == this.newMarker) { this.removeOverlays(marker) }
				this.polyPoints = this.polyPoints.without(marker.getLatLng());
			}
			this.logCoordinates();
			this.saveGuiState();
			this.drawCoordinates();
		}
	},

	drawCoordinates: function()
	{
		if (this.polyPoints.length > 1)
		{
			this.polySquare = new Array();
			this.polySquare.push(this.polyPoints[1]);
			this.polySquare.push(new GLatLng(this.polyPoints[1].lat(), this.polyPoints[0].lng()));
			this.polySquare.push(this.polyPoints[0]);
			this.polySquare.push(new GLatLng(this.polyPoints[0].lat(), this.polyPoints[1].lng()));
			this.polySquare.push(this.polyPoints[1]);

			this.polyShape = new GPolygon(this.polySquare, this.lineColor, this.lineWeight, this.opacity, this.fillColor, this.opacity);
			this.polyShapeBorder = new GPolygon(this.polySquare, this.lineColor, this.lineWeight, 1, 'none', 1);
			this.oldMarker = new GMarker(this.polySquare[this.polySquare.length - 3], { icon: this.oldIcon });
			this.newMarker = new GMarker(this.polySquare[this.polySquare.length - 1], { icon: this.newIcon });

			this.map.addOverlay(this.oldMarker);
			this.map.addOverlay(this.newMarker);
			this.map.addOverlay(this.polyShape);
			this.map.addOverlay(this.polyShapeBorder);
			this.areaSize = this.polyShapeBorder.getArea();
		}
		else if (this.polyPoints.length != 0)
		{
			this.polyShape = new GPolygon(this.polyPoints, this.lineColor, this.lineWeight, this.opacity, this.fillColor, this.opacity);
			this.newMarker = new GMarker(this.polyPoints[this.polyPoints.length - 1], { icon: this.newIcon });
			this.map.addOverlay(this.newMarker);
			this.map.addOverlay(this.polyShape);
			this.areaSize = 0;
		}
		this.logCoordinates();
	},

	hideContent: function()
	{
		this.map.clearOverlays();
		this.drawCoordinates();
	},

	logCoordinates: function()
	{
		$('locationMapPolygon').value = "";
		this.polyPoints.each(function(point)
		{
			$('locationMapPolygon').value += "(" + point.lat() + "," + point.lng() + "),";
		});

		this.updateInfoPanel();
		if (this.polyPoints.length > 1) { this.onChange() }
	},

	setPredefinedSelection: function()
	{
		if ($('locationMapPolygon').value != "")
		{
			this.polyPoints.clear();
			var preDefinedPolygon = $('locationMapPolygon').value.split('),');
			for (var i = 0; i < preDefinedPolygon.size(); i++)
			{
				var point = preDefinedPolygon[i];
				if (point != '')
				{
					var latitude = preDefinedPolygon[i].substring(point.indexOf('(') + 1, point.indexOf(','));
					var longitude = preDefinedPolygon[i].substring(point.indexOf(',') + 1);
					this.polyPoints.push(new GLatLng(latitude, longitude));
				}
			}
			if (this.polyPoints.size() >= 1)
			{
				return true
			}
		}
		return false;
	},

	saveGuiState: function()
	{
		var position = this.map.getCenter();
		var zoomLvl = this.map.getZoom();
		$('locationMapGuiLat').value = position.lat();
		$('locationMapGuiLng').value = position.lng();
		$('locationMapGuiZoomLvl').value = zoomLvl;
	},

	clearSelection: function(com)
	{
		if ($('locationMapPolygon')) { $('locationMapPolygon').value = "" }
		this.polyPoints.clear();
		this.removeOverlays('ALL');
		this.onChange();
	},

	removeOverlays: function(point)
	{
		if (this.newMarker != undefined && (point == 'ALL' || point == this.newMarker)) { this.map.removeOverlay(this.newMarker) };
		if (this.oldMarker != undefined && (point == 'ALL' || point == this.oldMarker)) { this.map.removeOverlay(this.oldMarker) };
		if (this.polyShape != undefined) { this.map.removeOverlay(this.polyShape) };
		if (this.polyShapeBorder != undefined) { this.map.removeOverlay(this.polyShapeBorder) };
	},

	updateInfoPanel: function()
	{
		if ($('infoContainer'))
		{
			var area = '-';
			var counter = 0;
			var total = this.places.size(); ;
			if (this.polyPoints[1] != undefined && this.polyPoints[0] != undefined)
			{
				if (this.areaSize >= 1000000) { area = (this.areaSize / 1000000).toFixed(2) + "km<sup>2</sup>" }
				else { area = this.areaSize.toFixed(2) + "m<sup>2</sup>" }

				var topBorder = (this.polyPoints[1].lat() >= this.polyPoints[0].lat()) ? this.polyPoints[1].lat() : this.polyPoints[0].lat();
				var bottomBorder = (this.polyPoints[1].lat() <= this.polyPoints[0].lat()) ? this.polyPoints[1].lat() : this.polyPoints[0].lat();
				var leftBorder = (this.polyPoints[1].lng() >= this.polyPoints[0].lng()) ? this.polyPoints[1].lng() : this.polyPoints[0].lng();
				var rightBorder = (this.polyPoints[1].lng() <= this.polyPoints[0].lng()) ? this.polyPoints[1].lng() : this.polyPoints[0].lng();

				this.places.each(function(point)
				{
					if (bottomBorder <= point[1] && point[1] <= topBorder)
					{
						if (rightBorder <= point[2] && point[2] <= leftBorder) { counter++ }
					}
				});
			}
			$('infoContainer').innerHTML = "selected: <strong>" + counter + "</strong> (of " + total + ")";
			$('infoContainer').innerHTML += "<br/>";
			$('infoContainer').innerHTML += "area: " + area;
		}
	},

	onChange: function(script)
	{
		if (this.onChangeScript != '' || this.onChangeScript != undefined || this.onChangeScript != null)
		{
			eval(this.onChangeScript);
		}
	}
}
