(function ($, undefined) {
	
	StoreLocator = {

		lat: 51.52098,
		lng: 6.29261,
		defZoom: 10,
		_markers: [],
		_windows: [],
		_searchString: '',
		searchLevels: { near: 20, far: 50 },
		_umkreis: 0,

		init: function(){
			this.initMap();
			this.bindEvents();
		},

		bindEvents: function(){
			$('#suchform').submit(function(e){
				e.preventDefault();
				StoreLocator.collectSearchInfo();
			});

			$('.store_list_item').live('click', function(){
				var _this = $(this),
					_a    = _this.find('a'),
					_vars = _a.attr('href'),
					_arr  = [];

				_vars = _vars.replace('#','');
				_arr  = _vars.split(',');
					// console.log(_arr);
				StoreLocator.focusOnStore({_index:_arr[0],lat:_arr[1],lng:_arr[2],zoom:13});
			});
		},

		initMap: function(){
			StoreLocator.latlng = new google.maps.LatLng(StoreLocator.lat, StoreLocator.lng);

			var settings = {
				zoom: 9,
				center: StoreLocator.latlng,
				mapTypeControl: false,
				mapTypeControlOptions: {
					style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
					},
				navigationControl: true,
				navigationControlOptions: {
					style: google.maps.NavigationControlStyle.SMALL,
					position: google.maps.ControlPosition.LEFT_CENTER
					},
				streetViewControl: true,
				streetViewControlOptions: {
					position: google.maps.ControlPosition.LEFT_CENTER
					},
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};

			StoreLocator._gmap = new google.maps.Map(document.getElementById('gmap'), settings);

			StoreLocator.setAllMarkers({energie:true,licht:true,elektro:true,industrie:true});
		},

		setAllMarkers: function(categories){
			$.each(Fachhandwerker, function(i,_val){
				if( (categories.energie && _val.energie) || (categories.licht && _val.licht) || (categories.elektro && _val.elektro) || (categories.industrie && _val.industrie) )
				{
					StoreLocator.setSingleMarker(_val);
				}
			});
		},

		setSingleMarker: function(_loc){

			var _pos = new google.maps.LatLng(_loc.lat,_loc.lng),
				spaMarker = new google.maps.Marker({
					position : _pos,
					map : StoreLocator._gmap,
				   	title : _loc.firma
				}),
				popupWindowHTML = '<div class="hw_window"><h4>'+_loc.firma+'</h4><p>'+_loc.strasse+'<br>'+_loc.plz+' '+_loc.ort+'</p><p>Tel.: '+_loc.telefon+'<br>Fax: '+_loc.fax+'</p><p><a href="mailto:'+_loc.email+'">Email</a> / <a href="'+_loc.www+'" target="_blank">Homepage</a></p></div>',
				infowindow = new google.maps.InfoWindow({
					content: popupWindowHTML
				});


			google.maps.event.addListener(spaMarker, 'click', function(){
					StoreLocator.closeAllInfoWindows();
					infowindow.open(StoreLocator._gmap,spaMarker);
					// spaMarker.setIcon(SpaLocator.Map.markerIcons.active);
				});

			google.maps.event.addListener(infowindow, 'closeclick', function(){
					// SpaLocator.Map.resetMarkerIcons();
					// $('#spa_data').children('.vcard').removeClass('hover');
				});

			StoreLocator._markers.push(spaMarker);
			StoreLocator._windows.push(infowindow);
		},

		collectSearchInfo: function(){

			StoreLocator._searchString = $.trim($('#suchform input[name=suchort]').val());
			StoreLocator._umkreis = $('#suchform select[name=umkreis]').val();
			StoreLocator._umkreis = parseInt(StoreLocator._umkreis,10);
			
			var _cats = StoreLocator.selectedCategories();

			// console.log(_cats);

			if( !StoreLocator._searchString || StoreLocator._searchString.length < 3 )
			{
				StoreLocator.updateSearchValue('');
				StoreLocator.clearMap();
				StoreLocator.setAllMarkers(_cats);
			}
			else
			{
				StoreLocator.askGoogle(StoreLocator._searchString);
			}
		},

		selectedCategories: function(){
			var _cats = {energie:false,elektro:false,licht:false,industrie:false};

			if( $('#suchform input[name=energie]').is(':checked') )
			{
				_cats.energie = true;
			}
			if( $('#suchform input[name=elektro]').is(':checked') )
			{
				_cats.elektro = true;
			}
			if( $('#suchform input[name=licht]').is(':checked') )
			{
				_cats.licht = true;
			}
			if( $('#suchform input[name=industrie]').is(':checked') )
			{
				_cats.industrie = true;
			}

			return _cats;
		},

		askGoogle: function(_ort){
			var geocoder = new google.maps.Geocoder();

			// console.log('Asking for '+_ort+',Deutschland');

			geocoder.geocode({ address: _ort+',Deutschland' }, function(results, status) {

				if( status == 'OK')
				{
					var result = {
							'formatted_address' : results[0].formatted_address,
							'lat' : results[0].geometry.location.lat(),
							'lng' : results[0].geometry.location.lng()
						};

					result.formatted_address = result.formatted_address.replace(', Deutschland', '');
					StoreLocator.focusMap(result,StoreLocator.defZoom);
					StoreLocator.updateSearchValue(result.formatted_address);
					StoreLocator.clearResults();
					StoreLocator.findCloseStores(result,StoreLocator.searchLevels.near)
				}
				else
				{
					alert('Es hab leider keine Ergebnisse für Ihre Suche.');
				}

			});
		},

		updateSearchValue: function(_new){
			$('#suchform input[name=suchort]').val(_new);
		},

		focusMap: function(mapLocation, zoom){
			// SpaLocator.Map.closeAllInfoWindows();
			StoreLocator._gmap.setCenter(new google.maps.LatLng(mapLocation.lat, mapLocation.lng));
			StoreLocator._gmap.setZoom(zoom);
		},

		calcDistance: function(lat1,lon1,lat2,lon2){
			var R = 6371,
				dLat = (lat2-lat1) * Math.PI / 180,
				dLon = (lon2-lon1) * Math.PI / 180, 
				a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1*Math.PI/180) * Math.cos(lat2*Math.PI/180) * Math.sin(dLon/2) * Math.sin(dLon/2),
				c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)),
				d = R * c;

			return d;
		},

		closeAllInfoWindows: function()
		{
			for(var i=0, max = StoreLocator._windows.length; i < max; i++)
			{
				StoreLocator._windows[i].close();
			}
		},

		clearMap: function()
		{
			for(var i=0, max = StoreLocator._markers.length; i < max; i++)
			{
				StoreLocator._markers[i].setMap(null);
			}
		},
		
		clearResults: function(){
			$('.map_results').html('');
		},
		
		findCloseStores: function(geoCenter,range){
			var _count = 0,
				_cats = StoreLocator.selectedCategories(),
				resultWrap = $('.map_results'),
				minDistance = 0;
				
				StoreLocator.clearMap();
				
				// if( range == StoreLocator.searchLevels.far )
				if( false )
				{
					minDistance = StoreLocator.searchLevels.near;
				}

				resultWrap.append('<h3>Fachhandwerker im Umkreis von '+StoreLocator._umkreis+'km</3>')

				$.each(Fachhandwerker, function(i,_val){
					if( (_cats.energie && _val.energie) || (_cats.licht && _val.licht) || (_cats.elektro && _val.elektro) || (_cats.industrie && _val.industrie) )
					{
						var distance = StoreLocator.calcDistance(geoCenter.lat,geoCenter.lng,_val.lat,_val.lng);

						// if( distance <= range && distance > minDistance )
						if( distance <= StoreLocator._umkreis )
						{
							// StoreLocator.setSingleMarker(_val);
							StoreLocator.setSingleMarker(_val);
							resultWrap.append('<div class="store_list_item"><h4>'+_val.firma+'</h4><p>'+_val.plz+' '+_val.ort+'</p><a href="#'+i+','+_val.lat+','+_val.lng+'"></a></div>');
						}

					}
				});

			//if( range == StoreLocator.searchLevels.near )
			if( false )
			{
				StoreLocator.findCloseStores(geoCenter,StoreLocator.searchLevels.far);
			}
		},

		focusOnStore: function(store){
			// console.log(store);
			StoreLocator.focusMap(store,store.zoom);
			StoreLocator.closeAllInfoWindows();
			StoreLocator._windows[store._index].open(StoreLocator._gmap,StoreLocator._markers[store._index]);
		}
	};
	
	$(function(){
		if( $('#fachhandwerker').length>0)
		{
			StoreLocator.init();
		}
	});
	
}(jQuery));


