function searchwidget()
{
	//this.name = 'searchwidget';
}

searchwidget.prototype.togglepanel = function()
{
	this.searchvisible = !this.searchvisible;

	if (this.searchvisible)
	{
		if (this.panelSearch == undefined)
		{
			this.createSearch();
			//this.createJumpto();
		}

		this.panelSearch.style.display = 'block';
	}
	else
		this.panelSearch.style.display = 'none';
	
}

searchwidget.prototype.showSearchResults = function()
{
	if (this.wndSearchResults == undefined || this.wndSearchResults.container == null)
		this.createSearchResultBox();

	//this.wndSearchResults.container.style.right = '320px';
		
	this.wndSearchResults.show();
}

searchwidget.prototype.hideSearchResults = function()
{
	this.wndSearchResults.hide();
}

searchwidget.prototype.updateSearch = function(event, inputelement)
{
	if (!event)
		event = window.event;

	// http://www.quirksmode.org/js/keys.html (?)
	var _this = this;
//	alert('object class = '+this.name+"\ninput value = "+inputelement.value);
//	setTimeout( function() { _this.doSearch(inputelement.value) } , 0 ); // we want the current to also be included
	setTimeout( function() { _this.doSearch() } , 100 ); // we want the current to also be included
//	stopPropagation(event);
		
}
/*
searchwidget.prototype.createJumpto = function()
{
	var eleminput = document.createElement('input');
	eleminput.type = 'text';
	eleminput.style.display = 'block';
	eleminput.style.marginTop= '50px';
	this.panelSearch.appendChild(eleminput);
	this.elemgotoinput = eleminput;
	
	var self = this;
	
	var elemgotopoint = document.createElement('button');
	elemgotopoint.innerHTML = 'Ga naar punt';
	elemgotopoint.onclick = function() { self.dopointsearch(); };
	this.panelSearch.appendChild(elemgotopoint);

	var elemgototrack = document.createElement('button');
	elemgototrack.innerHTML = 'Ga naar route';
	elemgototrack.onclick = function() { self.dotracksearch(); };
	this.panelSearch.appendChild(elemgototrack);
}
*/
searchwidget.prototype.dopointsearch = function(pointid)
{
	var self = this;
//	var pointid = parseInt(this.elemgotoinput.value);
	var point = mapmeta.fetchItemById(pointid, function(point){self.jumptopoint(point);});
}
searchwidget.prototype.jumptopoint = function(point)
{
	console.log(point);

	if (point == null)
	{
		alert('Onbekend punt.');
		return;
	}

	var pointid = point.id;

	console.log(point);
	
	// already on the correct map?
	if (mapmeta.mapid == point.mapid)
	{
		//mygmap.panToItemById(pointid);
		mygmap.centerOnItemById(pointid);
		mygmap.hoverpoint(pointid);
	}
	else
	{
		product.gotoMap(point.mapid);
		
		product.events.onceaftermaploaded = function()
		{
			mygmap.centerOnItemById(pointid);
			mygmap.hoverpoint(pointid);
			//var item = mapmeta.getItemById(pointid);
			//item.instance.setHover(true);
		}
	}
}

searchwidget.prototype.jumptotrack = function(track)
{
	console.log(track);

	if (track == null)
	{
		alert('Onbekende track.');
		return;
	}

	var trackid = track.id;

	// already on the correct map?
	if (track.mapid == mapmeta.mapid)
	{
		var itemid = mygmap.drawTrack(track);
		//mygmap.drawItemById
	
		// FIXME: center
		//mygmap.centerOnItemById(itemid);
		mygmap.hoverpoint(itemid);
	}
	// ADDME: move to other map
/*
	else
	{
		product.gotoMap(point.mapid);
		
		product.events.onceaftermaploaded = function()
		{
			mygmap.centerOnItemById(pointid);
			mygmap.hoverpoint(pointid);
			//var item = mapmeta.getItemById(pointid);
			//item.instance.setHover(true);
		}
	}
*/
}
searchwidget.prototype.dotracksearch = function(trackid)
{
	var self = this;
	//var trackid = parseInt(this.elemgotoinput.value);
	var point = mapmeta.loadTrackWithCallback(trackid, function(track){self.jumptotrack(track);});
}


searchwidget.prototype.createSearch = function()
{
	if ( this.panelSearch )
		return;
		
	var panelSearch = document.createElement('div');
	panelSearch.className = "panelSearch";
	
	var _this = this;
	
	var sbox = document.createElement('input');
	sbox.type = 'text';
	sbox.value = 'Zoeken...';
	sbox.className = 'searchEmpty';

	sbox.onfocus	= function(e)
						{
							if (!e) e = window.event;			// IE
							if (_this.panelSearchInput.value == "Zoeken...")
							{
								_this.panelSearchInput.value = "";
								removeClass(_this.panelSearchInput, "searchEmpty");
							}

							_this.showSearchResults();
							_this.updateSearch(e, this);
						}

	// steal ALL input when we are focussed
	sbox.onkeypress = function(event)
						{
							if (!event)
								event = window.event;			// IE

							//stopPropagation(e); <-- in Opera this also prevent typing in the <input>
						};

	// gets all keypresses (onkeypress doesn't fire on BACKSPACE in IE and SAFARI)
	sbox.onkeyup =
			function(event)
			{
				if (!event)
					event = window.event;			// IE

				var keyCode = (event.which === undefined) ? event.keyCode : event.which;

				// esq closes the searchresults panel
				if (keyCode == 27)
				{
					this.blur();
					event.preventDefault();
					return;
				}

				_this.updateSearch(event, this);
			};
	
	sbox.onblur	=
		 function(e)
			{
				// clicking an item in the searchresults may also blur the <input>
				// and cause the searchresults to be hidden before the onclick is fired.
				// (making it impossible to click a searchresult)
				// Therefore we delay hiding the searchresults.
				var _tempthis = _this;
				if (_this.panelSearchInput.value == "")
				{
					_this.panelSearchInput.value = "Zoeken...";
					addClass(_this.panelSearchInput, "searchEmpty");
				}
				setTimeout( function() { _tempthis.hideSearchResults(); } , 250 );
			};

	panelSearch.appendChild(sbox);
	this.panelSearchInput = sbox;

	/*
	panelSearch.appendChild(createCheckbox('chkMap', 'Zoek door de kaart', true, true));
	panelSearch.appendChild(createCheckbox('chkVideo', "Zoek door de video's", false, false));
	panelSearch.appendChild(createCheckbox('chkQuestions', "Zoek door de vragen", false, false));
	panelSearch.appendChild(createCheckbox('chkRoutes', "Zoek door de routes", false, false));
	*/

	this.panelSearch = panelSearch;
	this.panelcontainer.appendChild(panelSearch);
	
}

function createCheckbox(id, label, ischecked, enabled)
{
	var chkcontainer = document.createElement('div');
	chkcontainer.style.marginTop = '5px';

	var chk = document.createElement('input');
	chk.id = id;
	chk.type = 'checkbox';

	if (!enabled)
		chk.disabled = true;

	if (ischecked)
		chk.checked = true;
		
	var lbl = document.createElement('label');
	lbl["for"] = id;
	lbl.appendChild(document.createTextNode(label));

	chkcontainer.appendChild(chk);
	chkcontainer.appendChild(lbl);
	
	return chkcontainer;
}


searchwidget.prototype.doSearch = function(searchkey)
{
//	if (searchkey == '')
//	  return;

	if (searchkey == null)
		searchkey = this.panelSearchInput.value;

	console.log("Seaching for "+searchkey);
		
	var _this = this;
//	var searchkey = SPCTrim(searchkey)+""; // disabled cause when used toLowerCase() cuts of 2's at the end???!!!

	if (searchkey == '')
		var keycount = 0;
	else
	{
		searchkey    = searchkey.toLowerCase();
		var keyparts = searchkey.split(' ');
		var keycount = keyparts.length;
	}
	
	var body = document.createElement('div');
	body.className = 'searchResults';
	body.style.maxHeight = (document.body.clientHeight - 150)+'px';

	if (searchkey!="" && !isNaN(searchkey))
	{
		var category = document.createElement('div');
		category.className = "searchCategory";
		category.innerHTML = "Overig";
		body.appendChild(category);

		var entry = document.createElement('div');
		entry.className = 'searchEntry';
		entry.innerHTML = 'Zoek een punt met nummer '+searchkey;
		entry.onclick = function() { _this.dopointsearch(parseInt(searchkey)); }
		body.appendChild(entry);

		var entry = document.createElement('div');
		entry.className = 'searchEntry';
		entry.innerHTML = 'Zoek een route met nummer '+searchkey;
		entry.onclick = function() { _this.dotracksearch(parseInt(searchkey)); }
		body.appendChild(entry);
	}
	
	
	var availroom = /*getWindowSize().height*/ this.resultscontainer.offsetHeight - (this.wndSearchResults.container.offsetHeight - this.wndSearchResults.body.clientHeight);

	var   icount  = mapmeta.items.length
		, results = 0
	    , found;
	
	var resultitems = [];
	
	for(var tel=0; tel<icount; tel++)
	{
		var mapitem = mapmeta.items[tel];

		// skip anything that isn't a normal point
		if (mapitem.shape != 1 || !mapitem.published || mapitem.temporary )
			continue;
	
		mapitemname = mapitem.name.toLowerCase();

		found = true;
		
		if (keycount > 0)
		{
			for (var keynr = 0; keynr < keycount; keynr++) {
				if (mapitemname.indexOf( keyparts[keynr] ) == -1) {
					found = false;
					break;
				}
			}
		}
		
		if (found)
			resultitems.push(mapitem);
	}

	var results = resultitems.length;


	// sort results
	var strvar = "";
	if (strvar.localeCompare)
	{
		resultitems.sort(function(a,b) { return a.name.localeCompare(b.name); });
	}
	else
	{
		resultitems.sort(function(a,b) { return a.name > b.name });
	}
	
	
	
	
	var category = document.createElement('div');
	category.className = "searchCategory";
	category.innerHTML = "Punten in deze kaart";
	body.appendChild(category);
	
	for(var tel=0; tel<results; tel++)
	{
		var item = resultitems[tel];
		
		var entry = document.createElement('div');
		entry.className = 'searchEntry';
		entry.mapitemid = item.id;
		entry.onclick = function()
		{
			if (_this.onitemselect)
				_this.onitemselect(this.mapitemid /* attribute of element */);

			_this.wndSearchResults.hide(); //close();
		};

		if (item.photo)
			var photosrc = product.url.gallery+product.map+'/w160/'+item.photo;
		else
			var photosrc = product.url.gallery+product.map+'/w160/video/placeholder.png';

		var entryname = document.createElement('span');
		entryname.className = 'entryName';
		entryname.appendChild(document.createTextNode( item.name ));
		entry.appendChild(entryname);
/*
		var photo = document.createElement('img');
		photo.className = 'searchthumb';
		photo.style.width = '160px';
		photo.src = photosrc;
		entry.appendChild(photo);
*/
		body.appendChild(entry);
	}


	
//	var itemheight = (availroom-4*itemcount) / itemcount;

	if (results==0) {
//		body.style.margin = '5px 0px 5px 15px';
		body.appendChild(document.createTextNode('Geen resultaten gevonden voor zoekopdracht: '+searchkey));
	}

	console.warn("Replacing");
	
	this.wndSearchResults.results.parentNode.replaceChild(body, this.wndSearchResults.results);
	this.wndSearchResults.results = body;
}

searchwidget.prototype.createSearchResultBox = function() {

	this.wndSearchResults = product.openWindow(
										{ title:          'Zoekresultaten'
	                                    , className:      'mappopup searchresults'
										, canclose:       false
										, candrag:        false
										, visible:        false
										, center:         false
										, right:			315
										, top:				125
										, preferredWidth: 500
										});

	if (!useragent.csssupport.rgba) {
		var bg = document.createElement('div');
	    bg.className = 'background';
		this.wndSearchResults.body.appendChild(bg);
	}
/*
	var title = document.createElement('div');
	title.className = 'popupTitle';
	title.appendChild(document.createTextNode('Zoekresultaten:'));
	this.wndSearchResults.body.appendChild(title);
*/
	var results = document.createElement('div');
	this.wndSearchResults.body.appendChild(results);
	this.wndSearchResults.results = results;
	
//	this.wndSearchResults.container.style.right = (map.miniW + 35)+'px';
}
