﻿window.addEvent('domready', function () {

	// window.location.hash = "#hallo"
	
	
	// (function () {window.location.reload();}).periodical(30000);
	
	var clip = new ZeroClipboard.Client();
	clip.glue('copy-button');
	
	
	$('map').addEvent('update-links', function () {
		$$('img.wml-marker').each(function (img) {
			img.addEvent('click', function () {
				$$('.wml-info-window a').each(function (link) {
					link.set('target', '_blank');
				});
			});
		});
	});
	
	
	$('search').addEvent('disable', function () {
		$$('input').each(function (inp) {
			inp.set('disabled', true);
		});
	});
	
	$('search').addEvent('enable', function () {
		$$('input').each(function (inp) {
			inp.erase('disabled');
		});
	});
	
	$$('input').each(function (inp) {
		
		if (inp.get('placeholder') != null) {
			inp.addEvent('focus', function () {
				if(this.get('value') == this.get('placeholder')) {
					this.set('value', '');
				}
				this.removeClass('placeholder');
			});
			inp.addEvent('blur', function () {
				if(this.get('value') == "") {
					this.set('value', this.get('placeholder'))
					this.addClass('placeholder');
				}
			});
			
			inp.fireEvent('blur');
			
		}
	});
	
	$('country-container').set('value', 'germany');
	$('view').set('value', 'dealers');
	

	
		
	
	$$('#country-container input').each(function (inp) {		
		inp.addEvent('click', function () {
			$('country-container').set('value', this.get('value'));
			$('search').fireEvent('loading-xml');
			
				geocoder.getLocations(this.get('value'), function(response) {
					$('search').fireEvent('loading-xml');

					var southWest = new CM.LatLng(response.bounds[0][0], response.bounds[0][1]),
						northEast = new CM.LatLng(response.bounds[1][0], response.bounds[1][1]);
					map.zoomToBounds(new CM.LatLngBounds(southWest, northEast));
					// map.setZoom(map.getZoom()-1);
					$('search').fireEvent('update-hash');
				});
		});
	});
	

	$('loading').setStyle('display', 'none');
	$('loading-xml').setStyle('display', 'none');
	
	$('search').addEvent('loading', function () {
		if ($('loading').getStyle('display') == 'none') {
			$('search').fireEvent('disable');
			$('loading').setStyle('display', 'block');
			$('finder-button').setStyle('display', 'none');
		}
		else {
			$('search').fireEvent('enable');
			$('loading').setStyle('display', 'none');
			$('finder-button').setStyle('display', 'block');
		}
	});

	$('search').addEvent('loading-xml', function () {
		if ($('loading-xml').getStyle('display') == 'none') {
			$('search').fireEvent('disable');
			$('loading-xml').setStyle('display', 'block');
		}
		else {
			$('search').fireEvent('enable');
			$('loading-xml').setStyle('display', 'none');
		}
	});


	$('search').fireEvent('disable');
	var cloudmade = new CM.Tiles.CloudMade.Web({key: '23e260a42fe84d46b7b98a89fb0a7fb7', styleId: 1});
    var map = new CM.Map('map', cloudmade);
	
	var dealers = new CM.GeoXml('http://www.premium-cola.de/finder/dealers.kml');

	CM.Event.addListener(dealers, 'load', function () {
		
		$$('.wml-copyright-text a').each(function (a) {
			a.set('target', '_blank');
		});
		
		$('search').fireEvent('enable');
		map.addControl(new CM.LargeMapControl());
		map.addControl(new CM.ScaleControl(), new CM.ControlPosition(CM.TOP_RIGHT, new CM.Size(20, 20)));		
	
		map.zoomToBounds(dealers.getDefaultBounds());
		map.addOverlay(dealers);
		shownMap = dealers;
		$('map').fireEvent('update-links');
		
		if (window.location.hash != null) {
			h = window.location.hash;
			h = h.substr(1, h.length-1); 
			h = h.split('+');
			if (h[0] && h[1]) {
				$$('input').each(function (inp) {
					inp.set('checked', false);
				});

				$(h[0]).set('checked', true);
				// $(h[1]).set('checked', true);

			//	$(h[0]).fireEvent('click');
				$(h[0]).fireEvent('click');			
				
				ll = h[1];
				ll = ll.split(',');
				
				
				//ounds
				if (ll[0] && ll[1] && ll[2] && ll[3]) {
					map.zoomToBounds(  new CM.LatLngBounds( new CM.LatLng(ll[0], ll[1]), new CM.LatLng(ll[2], ll[3]) )  );
				}
				//no bounds
				if (ll[0] && ll[1] && ll.length < 3) {
					(function () {
					var offset = .001
					lo = parseFloat(ll[0]);
					la = parseFloat(ll[1]);
					var latlngs = [
					    new CM.LatLng(lo-(offset*.6), la-offset),
					    new CM.LatLng(lo-(offset*.6), la+offset),
					    new CM.LatLng(lo+(offset*.6), la+offset),
					    new CM.LatLng(lo+(offset*.6), la-offset)
					];
					
					
					var polygon = new CM.Polygon(latlngs, '#ee0000');
				
			        map.addOverlay(polygon);
					markers.push(polygon);
					}).delay(500);
					map.setZoom(15);
					map.setCenter(new CM.LatLng(ll[0], ll[1]));
				}
				
			}
			else {
				$('search').fireEvent('update-hash');
			}
		}
		
		$('search').addEvent('update-hash', function () {
			var b = [map.getBounds().getSouthWest(), map.getBounds().getNorthEast()]; 
			var co = 0;
			
			b.each(function (c) {
				c = c.toString();
				c = c.substring(1, c.length-2);
				c = c.split(', ');
				c = c.join(',');
				b[co] = c;
				co++;
			});
			
			
			window.location.hash = '#' + $('view').get('value') + '+' + b.join(',');
			clip.setText(window.location.href);
			$('copy-input').set('value', window.location.href);
			
		});
		
		$('search').fireEvent('update-hash');
		
		
		CM.Event.addListener(map, 'moveend', function () {
			$('search').fireEvent('update-hash');
		});
		
		CM.Event.addListener(map, 'zoomend', function () {
			$('search').fireEvent('update-hash');
		});
		
		
	});
	


	$$('#view input[type=radio]').each(function (chkbox) {		
		chkbox.addEvent('click', function (e) {
			
				if (this.get('value') == 'locations') {
					v = "locations";
					d = 'http://www.premium-cola.de/finder/locations.kml';
				}
				if (this.get('value') == 'speakers') {
					v = "speakers";
					d = 'http://www.premium-cola.de/finder/speakers.kml';
				
				}
				if (this.get('value') == 'dealers') {
					v = "dealers";
					d = 'http://www.premium-cola.de/finder/dealers.kml';
				}
		
				$('search').fireEvent('loading-xml');
			
				map.removeOverlay(shownMap);
				
				$('view').set('value', v);
				$('search').fireEvent('update-hash');
				
				CM.Event.addListener(new CM.GeoXml(d), 'load', function () {
					$('search').fireEvent('loading-xml');
					map.addOverlay(this);
					shownMap = this;
					
					$('map').fireEvent('update-links');
				});
		});
	});

	var markers = new Array();
	var geocoder = new CM.Geocoder('23e260a42fe84d46b7b98a89fb0a7fb7');


	var interpreter = {
		process: function (v) {
			
			v = v.replace(/,(\s)*(Germany|Austria|Switzerland|Deutschland|Schweiz|Österreich)/i, '').replace(/straße/i, 'str').replace(/str(\.)?/i, 'straße');			
			
			//Kiel hack
			if ($('finder-zip').get('value') != 'Kiel') 
				v = v + ', ' + $('country-container').get('value');	
			
			return v;
		}
	};

	$('finder-button').addEvent('click', function () {
		if ($('finder-zip').get('value') != '' && $('finder-zip').get('value') != $('finder-zip').get('placeholder')) {
			$('search').fireEvent('loading');
			
			
			if ($('finder-street').get('value') != "" && $('finder-street').get('value') != $('finder-street').get('placeholder')) {
				var val = $('finder-street').get('value') + ', ' + $('finder-zip').get('value');
			}
			else {
				var val = $('finder-zip').get('value');
			}
			
			
			markers.each(function (m) {
				m.hide();
			});
			
			
			geocoder.getLocations(interpreter.process(val), function(response) {
				$('search').fireEvent('loading');
				
				
				if (response.features.length > 1) {
					alert('Es wurde mehr als ein Ergebnis gefunden, bitte klicke auf den gewünschten Ort (1-' + response.features.length + ')');
		            
				
					for (var i = 0; i < response.features.length; i++) {
						 var coords = response.features[i].centroid.coordinates;
					        var marker = new CM.Marker(new CM.LatLng(coords[0], coords[1]), {
					            title: response.features[i].properties.name,
								icon: new CM.Icon({image: '/finder/images/no/'+ (i+1) + '.png', iconSize: new CM.Size(20, 20)})
							});
					       
							CM.Event.addListener(marker, 'click', function (ll) {
								map.setZoom(16);
								map.setCenter(this.getLatLng());
								map.setZoom(15);
							});
					
					        map.addOverlay(marker);
							markers.push(marker);
					    }
				}
				
				var southWest = new CM.LatLng(response.bounds[0][0], response.bounds[0][1]),
				northEast = new CM.LatLng(response.bounds[1][0], response.bounds[1][1]);
				map.zoomToBounds(new CM.LatLngBounds(southWest, northEast));
			}, {resultsNumber: 15});
		}
		else {
			alert ('Bitte gebe mindestens eine Stadt ein, wo du suchen möchtest. (z.B. Berlin)')
		}
	});
	
	$('finder-zip').addEvent('keydown', function (e) {
		e = new Event(e)
		if (e.key == 'enter')  {
			$('finder-button').fireEvent('click');
		}
	});
	$('finder-street').addEvent('keydown', function (e) {
		e = new Event(e)
		if (e.key == 'enter')  {
			$('finder-button').fireEvent('click');
		}
	});


});
