var ZipSearch = new Class({
	options: {
		delay: 1000,
		autozoom: false
	},
	initialize: function(element, options) {
		this.element = $(element);
		var self = this;
		this.element.addEvent('keydown', function(event){
			if (event.code == 13)
				self.updateMarker();
		});
		this.radius = 0;
		this.bounds = null;
		/*
		this.observer = new Observer(this.element, this.updateMarker.bind(this), $merge({
			'delay': this.options.delay
		}, this.options.observerOptions));
		*/
	},
	
	getBounds: function() {
		return this.bounds;
	},
	
	setRadius: function(radius) {
		this.radius = radius;
	},
	
	updateMarker: function() {
		var txtNotFound = $('notFound');
		var txtInvalid = $('invalid');
		var txtShort = $('tooShort');
		txtNotFound.style.display = 'none';
		txtInvalid.style.display = 'none';
		txtShort.style.display = 'none';
		
		if (map == null || map == undefined)
			return;
		this.bounds = new GLatLngBounds(); 
		var center = null;
		
		// check entered zip code
		if (this.element.value.length < 2) {
			// do not search for very short zips (takes MUCH too long)
			txtShort.style.display = 'inline';
			return;
		}
		
		// check if zip code is invalid
		if(isNaN(this.element.value) || this.element.value.length > 5 || (this.element.value.length == 5 && !GeoZips[this.element.value])) {
			txtInvalid.style.display = 'inline';
			txtNotFound.style.display = 'none';
			txtShort.style.display = 'none';
			return;
		}
		
		// get bounds from geozips.js if full zip code has been entered
		if (this.element.value.length == 5) {
			this.bounds.extend(GeoZips[this.element.value]);
			center = GeoZips[this.element.value];
		}
		else { //We have to find our center
			for (var i in GeoZips) {
				if (i.indexOf(this.element.value) === 0) {
					this.bounds.extend(GeoZips[i]);
					center = GeoZips[i];
					break;
				}
			}
		}
		var found = false;
		
		for (var i = 0; i < custlocs.length; i++) {
			var c = custlocs[i];
			c.setCounter(i);
			//var re = new RegExp("^" + this.element.value);

			//If beginning of zip code from accoustician is the same as our search string
			if (c.zip.indexOf(this.element.value) === 0) {
				found = true;
				c.showMarker();
				this.bounds.extend(c.getPoint());
				if (center == null)
					center = c.getPoint();
			}
			else {
				c.hideMarker();
			}
		}
		if (this.radius > 0) {
			for (var i = 0; i < custlocs.length; i++) {
				var c = custlocs[i];
				if (center != null && center.distanceFrom(c.getPoint()) < this.radius) {
					found = true;
					c.showMarker();
					this.bounds.extend(c.getPoint());
				}
			}
		}
		if(found == false) {
			txtNotFound.style.display = 'inline';
			txtInvalid.style.display = 'none';
			txtShort.style.display = 'none';
		}
		if (this.options.autozoom && map !== null) {
			// ===== determine the zoom level from the bounds =====
			var zoomLvl = this.getZoomLevel();
			map.setZoom(zoomLvl);
			// ===== determine the centre from the bounds ======
			map.panTo(this.bounds.getCenter());
		}
		// center map if no address could be found
		if(center == null) {
			map.setCenter(new GLatLng(glat, glng),5,G_NORMAL_MAP);
		}
		
		this.listAddresses();
	},
	
	getZoomLevel: function() {
		return map.getBoundsZoomLevel(this.bounds) > 14 ? 14 : map.getBoundsZoomLevel(this.bounds);
	},
	
	toggleAutozoom: function() {
		var self = this;
		if (this.options.autozoom) {
			this.options.autozoom = false;
		}
		else {
			this.options.autozoom = true;
			this.updateMarker();
		}
	},
	
	listAddresses: function() {
		var singleAddress = '';
		var output = '';
		var address = new Array();
		var classPos = '';
		for(var i=0, j=0;i<custlocs.length;i++) {
			loc = custlocs[i];
			if(loc.isHidden()==false && loc.acoustician.length>0) {	
				if(j%2==0) {
					classPos = 'first';
				} else {
					classPos = 'last';
				}
				singleAddress = '<div class="block '+classPos+'">' + loc.name + '<br />' + loc.street + '<br />' + loc.zip + ' ' + loc.city + '<br />' + loc.phone +
				'<br />' + '<a class="mapLink" href="'+location.href+'" onclick="return goToAddress(custlocs['+i+']);">Zur Karte</a></div>';
				if(j%2==0) {
					singleAddress = '<div class="blockWrap">' + singleAddress;
				} else {
					singleAddress = singleAddress + '<div class="clear"></div></div>';
				}
				output = output + singleAddress;
				j++;
			}
		}
		$('listAddresses').set('html',output);
	}
});

ZipSearch.implement(new Options);
goToTop = null;
goToAddress = null;
window.addEvent('domready', function() {
	var zipSearch = new ZipSearch('zipSearch');
	var autozoomLink = $('autozoom');

	if (autozoomLink.checked == true)
		zipSearch.toggleAutozoom();

	autozoomLink.addEvent('click', function() {
		zipSearch.toggleAutozoom()
	});
	
	$('startSearch').addEvent('click', function() {
		zipSearch.updateMarker();
	});
	
	var mySlide = new Slider($('area'), $('knob'), {
		offset: 0,
		range: [0,50],
		onChange: function(pos) {
			$('upd').set('html', pos+' km');
			zipSearch.setRadius(pos*1000);
			this.set(pos);
		}
		/*steps: 6,
		snap: true,
		onChange: function(step){
			switch (step) {
				case 0: 
					$('upd').set('html', "0 km");
					zipSearch.setRadius(0);
					break;
				case 1:
					$('upd').set('html', "5 km");
					zipSearch.setRadius(5000);
					break;
				case 2:
					$('upd').set('html', "10 km");
					zipSearch.setRadius(10000);
					break;
				case 3:
					$('upd').set('html', "20 km");
					zipSearch.setRadius(20000);
					break;
				case 4:
					$('upd').set('html', "30 km");
					zipSearch.setRadius(30000);
					break;
				case 5:
					$('upd').set('html', "50 km");
					zipSearch.setRadius(50000);
					break;
			}
			this.set(step);
		}
		*/
	}).set(5);
	
	var scroll = new Fx.Scroll(window, { offset: {'x': 0, 'y': 0} });
	goToTop = function() { scroll.toElement('mainContent'); }

	goToAddress = function(loc) {
		var loc = loc;
		var scroll = new Fx.Scroll(window, { offset: {'x': 0, 'y': 0} });
		
		scroll.toElement('mainContent').chain(function() {
		map.setZoom(zipSearch.getZoomLevel());
		map.panTo.delay(1000, map, loc.getPoint());
		map.setZoom.delay(2000, map, 14);
		//map.panBy(map.getCenter().distanceFrom(loc.getPoint()));
		this.start.delay(500, this);
		}).chain(function() {
		//map.setZoom(14);
		loc.marker.openInfoWindowHtml(loc.getHtml());});
		return false;
	}		
});
