var map;
var geocoder;
var markers = [];
var markerCluster;
var defaultZoom;

var findedLocation = [];

var openedWindow = null;

var styles = [{
		"url": '/_clip/master-group.png',
		"height": 40,
		"width": 40,
		"opt_textColor": 'white',
		"opt_textSize":12
	},
	{
		"url": '/_clip/master-group.png',
		"height": 40,
		"width": 40,
		"opt_textColor": 'white',
		"opt_textSize":12
	},
	{
		"url": '/_clip/master-group.png',
		"height": 40,
		"width": 40,
		"opt_textColor": 'white',
		"opt_textSize":12
}];

function initMap(startzoom)
{
	defaultZoom = (startzoom) ? startzoom : 7; 

	var myOptions = {
	  zoom: getStartZoom(),
	  center: getStartLatLng(),
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	geocoder = new google.maps.Geocoder();
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	google.maps.event.addListener(map, 'zoom_changed', function() {
		zoom = map.getZoom();
		// name, value, expires, path, domain, secure
		Set_Cookie('GZoom', zoom, '', '/', document.location.host, '');
	});

	google.maps.event.addListener(map, 'dragend', function() {
		center = map.getCenter();
		Set_Cookie('GLatLng', center.toUrlValue(), '', '/', document.location.host,'');
	});


//	google.maps.event.addListener(map, 'tilesloaded', function() {
//		//alert('tilesloaded');
//		$('#map_loader').hide();
//	});

	if (document.getElementById("city").value != '')
	{
		showCity();
	}
	//loadKml();
}

function showCity()
{
	selectedCity = document.getElementById("city").value;
	selectedCountry = document.getElementById("country").value;
	selectedIndex = document.getElementById("country").options.selectedIndex;
	country = document.getElementById("country").options[selectedIndex].text;
	city = selectedCity + ", " + country;
	if (geocoder) {
		geocoder.geocode( { 'address': city}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);
				Set_Cookie('GLatLng', results[0].geometry.location.toUrlValue(), '', '/', document.location.host,'');
			} else {
				alert("Geocode was not successful for the following reason: " + status);
			}
		});
	}
}

function loadKml()
{
	dt=new Date();
	has13 = (document.getElementById('has13').checked == true) ? 1 : 0;
	has15 = (document.getElementById('has15').checked == true) ? 1 : 0;
	has18 = (document.getElementById('has18').checked == true) ? 1 : 0;
	ritual = (document.getElementById('ritual').checked == true) ? 1 : 0;
	cash_and_carry = (document.getElementById('cash_and_carry').checked == true) ? 1 : 0;

	var markersLayer = new google.maps.KmlLayer("http://"+document.location.host + "/smallapp/placemarks/has13=" + has13 + "&has18=" + has18 + "&has15=" + has15 + "&cash_and_carry=" + cash_and_carry + "&ritual=" + ritual + "&stamp="+dt.getTime()+"/", {preserveViewport:true});
	markersLayer.setMap(map);
}

function loadMarkers(filter)
{
	var dt=new Date();
	var fa = {};

	if (filter)
	{
		fa.has13 = (document.getElementById('has13').checked == true) ? 1 : 0;
		fa.has15 = (document.getElementById('has15').checked == true) ? 1 : 0;
		fa.has18 = (document.getElementById('has18').checked == true) ? 1 : 0;
		fa.ritual = (document.getElementById('ritual').checked == true) ? 1 : 0;
		fa.obchody = (document.getElementById('obchody').checked == true) ? 1 : 0;
	//	fa.cash_and_carry = (document.getElementById('cash_and_carry').checked == true) ? 1 : 0;
		fa.beer_container = $('#beer_container').val();
	}

	var url ="http://"+document.location.host + "/smallapp/markers/?stamp="+dt.getTime();
	//$.post(url, {"has13":has13,"has18":has18,"has15":has15,"ritual":ritual,"beer_container":beer_container}, loadMarkersCallback, 'json');
	$.post(url, fa, loadMarkersCallback, 'json');
}

function loadMarkersCallback(data)
{
	if (markers.length)
	{
		if (markerCluster)
		{
			markerCluster.clearMarkers();
		}
		markers = [];
	}
	$.each(data.markers, function(key, value) {
		var title = value.name;
		var descr = value.description;
		var icon = value.icon;

		var infowindow = null;

		var latLng = new google.maps.LatLng(parseFloat(value.lat), parseFloat(value.lng));
        var marker = new google.maps.Marker({"position": latLng, "icon": icon,"title": title});
		if (jQuery.browser.msie)
		{
			infowindow = new google.maps.InfoWindow({
				content: descr
			});

			google.maps.event.addListener(marker, 'click', function() {
				infowindow.open(map,marker);
			});
		} else {
			infowindow = new InfoBox({"content": descr});
			google.maps.event.addListener(marker, 'click', function() {
				if (openedWindow)
				{
					openedWindow.close();
					openedWindow = null;
				}
				infowindow.open(map,marker);
				openedWindow = infowindow;
			});
		}
        markers.push(marker);
	});



//	alert('test2');
//
//	$(data).find('Placemark').each(function(){
//		var title = $(this).find('name').text();
//		var descr = $(this).find('description').text();
//		var icon = $(this).find('href').text();
//		var coords = $(this).find('coordinates').text().split(",");
//		// pozor - KML ma obracene souradnice
//		var latLng = new google.maps.LatLng(coords[1], coords[0]);
//        var marker = new google.maps.Marker({"position": latLng, "icon": icon,"title": title});
//		//var infowindow = new google.maps.InfoWindow({content: descr});
//		var infowindow = new InfoBox({"content": descr, "boxStyle": {"opacity": 0.75, "width": "280px"}});
//		google.maps.event.addListener(marker, 'click', function() {
//			infowindow.open(map,marker);
//		});
//        markers.push(marker);
// 	});

	markerCluster = new MarkerClusterer(map, markers, {"styles":styles});
	$('#map_loader').hide();
}

function getStartLatLng()
{
	if (Get_Cookie('GLatLng'))
	{
		cookie_GlatLng = Get_Cookie('GLatLng').split(",");
		center = new google.maps.LatLng(cookie_GlatLng[0], cookie_GlatLng[1]);
	} else {
		center = new google.maps.LatLng(49.8, 15.5);
	}
	return center;
}

function getStartZoom()
{
	zoom = defaultZoom;
	if (Get_Cookie('GZoom'))
	{
		zoom = parseInt(Get_Cookie('GZoom'));
	}
	return zoom;
}

var searchPanelHidden = true;
function togglSearchPanel()
{
	if (searchPanelHidden)
	{
		$('#box-toggler').css('background', 'transparent url(/_clip/finder-arrow-right.png) 0 0 no-repeat');
		$("#filter-box").animate({"right": "+=330px"}, "slow");
		searchPanelHidden = false;
	} else {
		$('#box-toggler').css('background', 'transparent url(/_clip/finder-arrow-left.png) 0 0 no-repeat');
		$("#filter-box").animate({"right": "-=330px"}, "slow");
		searchPanelHidden = true;
	}
}

function zoomToResult()
{
	map.setZoom(15);
}

function goToResult()
{
	map.setCenter(findedLocation['latlng']);
	var marker = new google.maps.Marker({position: findedLocation['latlng'], map:map, title:findedLocation['title']});
	zoomToResult();
	Set_Cookie('GLatLng', findedLocation['latlng'].toUrlValue(), '', '/', document.location.host,'');
}

function setGeocodingLocation(info)
{
	findedLocation['latlng'] = new google.maps.LatLng(info.latitude, info.longitude);
	findedLocation['label'] = info.label;
}

function mapResults(results)
{
	return {
		label:  results[0].formatted_address,
		value: results[0].formatted_address,
		latitude: results[0].geometry.location.lat(),
		longitude: results[0].geometry.location.lng()
	}
}

function searchButtonClick()
{
	if (findedLocation.length == 0)
	{
		if (geocoder) {
			selectedCity = document.getElementById("city").value;
			geocoder.geocode( { 'address': selectedCity}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					info = mapResults(results);
					setGeocodingLocation(info);
					goToResult();
				} else {
					alert("Geocode was not successful for the following reason: " + status);
				}
			});
		}
	} else {
		goToResult();
	}


}

function filterButtonClick()
{
	$('#map_loader').show();
	loadMarkers(true);
}

function clearfilterButtonClick()
{
	$('#has13').attr('checked', false);
	$('#has15').attr('checked', false);
	$('#has18').attr('checked', false);
	$('#ritual').attr('checked', false);
	$('#obchody').attr('checked', false);
	$('#map_loader').show();
	loadMarkers(false);
}
