var storeSearch = {
	
	container: null,
	countries: {},
	center: { lat: 50.916887, lng: 10.239258 },
	zoom: 8,
	locationPlaceholder: "PLZ / Ort",
	map: null,
	markers: [],
	infoWindows: [],
	stores: [],
	bounds: null,
	lastAddress: false,
	icon: null,
	shaddow: null,
	detailsButton: "Details",
	
	init: function(container, options)
	{
		// set container
		this.container = $(container);
		
		if(this.container.length)
		{
			// get available countries
			if(typeof(options.countries) != "undefined")
				this.countries = options.countries;

			// get default center of map
			if(typeof(options.center) != "undefined")
				this.center = options.center;

			// set default zoom status of map
			if(typeof(options.zoom) != "undefined")
				this.zoom = options.zoom;

			// set zip placeholder
			if(typeof(options.zipPlaceholder) != "undefined")
				this.zipPlaceholder = options.zipPlaceholder;

			// set image
			if(typeof(options.image) != "undefined")
				this.image = options.image;

			// set details button label
			if(typeof(options.detailsButton) != "undefined")
				this.detailsButton = options.detailsButton;
				
			this.generateMapHTML();

			$('#store_search_location').bind("blur", function()
			{
				storeSearch.search();
			});

			$('#store_search_location').bind("keydown", function(e)
			{
				if(e.keyCode == 13)
					storeSearch.search();
			});

			$('#store_search_country').bind("change", function()
			{
				storeSearch.search();
			});
			
			
			if($.cookie('store_search_country') && $.cookie('store_search_address'))
			{
				$('#store_search_location').attr("value", $.cookie('store_search_address'));
				$('#store_search_country').attr("value", $.cookie('store_search_country'));
				
				storeSearch.search();
			}
		}
	},
	
	generateMapHTML: function()
	{
		var html = '\
			<input type="text" id="store_search_location" placeholder="'+this.locationPlaceholder+'" value="" />\
			<select id="store_search_country">';
		
		for(var code in this.countries)
		{
			html += '<option value="'+code+'">'+this.countries[code]+'</option>';
		}
		
		html += '\
			</select>\
			\
			<div id="store_search_map"></div>';
		
		this.container.html(html);
		
		var map_options = 
		{
			zoom: this.zoom,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		
		this.map = new google.maps.Map(document.getElementById("store_search_map"), map_options);
		this.map.setCenter(new google.maps.LatLng(this.center.lat, this.center.lng));
	},
	
	addMarker: function(lat, lng, type, options)
	{
		// if we dont have options create new object
		if(typeof(options) != "object")
			options = {};
			
		// set marker options
		options.position = new google.maps.LatLng(lat, lng);
		options.map = storeSearch.map;
		
		var info_window = false;
		if(options.infoWindow)
		{
			info_window = options.infoWindow;
			delete options.infoWindow;
		}
		
		if(type == "shop")
		{
			options.animation = google.maps.Animation.DROP;
			options.icon = this.image;
		}

		// create marker
		var marker = new google.maps.Marker(options);
		
		// ad markers to markers array to be able to remove them
		storeSearch.markers.push(marker);
		
		if(storeSearch.bounds == null)
			storeSearch.bounds = new google.maps.LatLngBounds();
		
		if(info_window)
		{
			var my_info_window = new google.maps.InfoWindow({
			    content: info_window
			});
			
			storeSearch.infoWindows.push(my_info_window);
			
			google.maps.event.addListener(marker, 'click', function() 
			{
				storeSearch.closeAllInfoWindows();
				my_info_window.open(storeSearch.map, marker);
			});
		}
		
			
		storeSearch.bounds.extend(marker.getPosition());
	},
	
	deleteMarkers: function()
	{
		for(var i in storeSearch.markers)
		{
			storeSearch.markers[i].setMap(null);
		}
		
		storeSearch.bounds = null;
		storeSearch.infoWindows = [];
		
	},
	
	zoomMap: function(zoomlevel)
	{
		if(typeof(zoomlevel) == "undefined")
		{
			storeSearch.map.fitBounds(storeSearch.bounds)
		}
		else
		{
			storeSearch.map.setZoom(zoomlevel);
		}
	},
	
	// search for stores
	search: function()
	{
		var zip = $('#store_search_location').attr("value");
		var country = $('#store_search_country').attr("value");
		
		if(this.lastAddress != zip+country)
		{
			this.lastAddress = zip+country;
			
			$.cookie('store_search_address', zip, { expires: 14, path: '/'});
			$.cookie('store_search_country', country, { expires: 14, path: '/'});
			
			if(zip.length >= 4 && country)
			{
				// get coordinates of entered address
				this.getCoordinates(zip, country, function(data)
				{
					if(data)
					{
						// delete all markers
						storeSearch.deleteMarkers();

						// create marker at center (current location)
						storeSearch.addMarker(data[1], data[0]);

						// and set center
						storeSearch.map.setCenter(new google.maps.LatLng(data[1], data[0]));

						// get stores
						storeSearch.getStores(data[1], data[0], storeSearch.displayStores);
					}
				});
			}
		}
	},
	
	// get stores from backend
	getStores: function(lat, lng, callback)
	{
		$.getJSON("/store_search/search/json/", { lat: lat, lng: lng }, function(data)
		{
			if(typeof(callback) == "function")
			{
				callback(data);
			}
		})
	},
	
	closeAllInfoWindows: function()
	{
		for(var i in storeSearch.infoWindows)
		{
			storeSearch.infoWindows[i].close();
		}
	},
	
	// display stores on the page
	displayStores: function(data)
	{
		storeSearch.stores = data;
		
		for(var i in storeSearch.stores)
		{
			var store = storeSearch.stores[i];
			
			storeSearch.addMarker(store.lat, store.lng, "shop", {
				infoWindow: '<strong>'+store.name+'</strong><br />\
					'+store.address+'<br />\
					'+store.zipcode+' '+store.city+'<br />\
					<a href="'+base_path+'/store_search/store/'+store.id+'">'+storeSearch.detailsButton+' »</a>'
			});
		}
		
		storeSearch.zoomMap();
	},
	
	// get coordinates of an address
	getCoordinates: function(address, country, callback)
	{
		$.getJSON("/store_search/get_cooridnates_of_address/", { address: address+","+country }, function(data)
		{
			if(typeof(callback) == "function")
			{
				callback(data);
			}
		})
	}
}
