var map=null;
var mapmarker = null;
var geocoder=null;
var debug = false;
var gmarkers=[];
var firmmarkers=[];
var firmdescriptions=[];
var firmaddress=[];

var tinyIcon = new GIcon();
tinyIcon.image = "http://krispol.pl/images/marker.png";
tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
tinyIcon.iconSize = new GSize(12, 20);
tinyIcon.shadowSize = new GSize(22, 20);
tinyIcon.iconAnchor = new GPoint(6, 20);
tinyIcon.infoWindowAnchor = new GPoint(5, 1);
//zIndexProcess:fixOrder, 
var markerOptions = { icon:tinyIcon, draggable: true };

var tinyIcon2 = new GIcon();
tinyIcon2.image = "http://krispol.pl/images/marker.png";
tinyIcon2.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
tinyIcon2.iconSize = new GSize(18, 26);
tinyIcon2.shadowSize = new GSize(24, 22);
tinyIcon2.iconAnchor = new GPoint(6, 20);
tinyIcon2.infoWindowAnchor = new GPoint(5, 1);

var markerOptions2 = { icon:tinyIcon2 };

var lat = 51.91933809194015;
var lng = 19.1451358795166;

function gElem(id) {
	var obj = document.getElementById(id);
	return document.getElementById(id);
}

function addItemToMap(lat,lng,desc){
	if(gElem("googlemap") && map != null){
		var firmcount = firmmarkers.length;
		firmmarkers[firmcount] = new GMarker(new GLatLng(lat, lng), markerOptions2);
		var last = firmmarkers.length - 1;
		firmdescriptions[last] = desc;
		GEvent.addListener(firmmarkers[last], "mouseover", function() {
			var myHtml = "<b>" + firmdescriptions[last] + "</b>";
			firmmarkers[last].openInfoWindowHtml(myHtml);
		});
		GEvent.addListener(firmmarkers[last], "click", function() {
			var myHtml = "<b>" + firmdescriptions[last] + "</b>";
			firmmarkers[last].openInfoWindowHtml(myHtml);
		});
		map.addOverlay(firmmarkers[firmcount]);
		//firmmarkers[firmcount].hide();
		$('#distribution_list').append(firmdescriptions[last] + '<div class="hr1"></div>');
		
	}
}

var startlat = 51.920;
var startlng = 19.146;

var point = new GLatLng(startlat, startlng);

var crazymarker = null;

function addSearchMarker() {
	
	if(crazymarker != null) { 
		map.removeOverlay(crazymarker);
	}	
	var newpoint = new GLatLng(startlat, startlng);
	crazymarker = new GMarker(newpoint, markerOptions);
	map.addOverlay(crazymarker);
}

var search_active = true;

function showAddress(location){	

	$('#distribution_list').text('');
	
	if(search_active)
	{
		//search_active = false;
		var location = location + " " + $("#distribution_county").val() + ", POLAND";
		geocoder=new GClientGeocoder();
		geocoder.setBaseCountryCode("PL"); 
		if(geocoder){
			geocoder.getLatLng(location,function(searchpoint){
				if(searchpoint){
					
					if(crazymarker !=null)
						crazymarker.setLatLng(searchpoint);
					
					point = searchpoint;
					map.setCenter(searchpoint, 6);
					if(firmmarkers.length > 0 && map !=null) 
					{
					  	for (var i=0;i<firmmarkers.length;i++) 
						{
					  		//firmmarkers[i].hide();
						}
					}
					$("#distribution_search").addClass("active");
				} else {
					if(firmmarkers.length > 0 && map !=null) 
					{
					  	for (var i=0;i<firmmarkers.length;i++) 
						{
					  		//firmmarkers[i].hide();
						}
					}
					$("#distribution_search").removeClass("active");
				}
			});
		} else { 
			alert('no geocoder');
		}
	}
}

function EnableSearch(){
	search_active = true;
}


function deg2rad(angle) {
    return (angle/180)*Math.PI;
}

function getDistance($lat1, $lon1, $lat2, $lon2) {
    $latd = deg2rad($lat2 - $lat1);
    $lond = deg2rad($lon2 - $lon1);
    $a = Math.sin($latd / 2) * Math.sin($latd / 2) +
         Math.cos(deg2rad($lat1)) * Math.cos(deg2rad($lat2)) *
         Math.sin($lond / 2) * Math.sin($lond / 2);
         $c = 2 * Math.atan2(Math.sqrt($a), Math.sqrt(1 - $a));
    return 6371.0 * $c;
}


function checkAll()
{
	if($("#distribution_search").hasClass("active")){
		var maxdistance = parseFloat(document.getElementById('distance').value);
		
		$('#distribution_list').text('');
		if(maxdistance==NaN) maxdistance = 100;
		if(maxdistance > 100) maxdistance = 100;
		
		var resultCount = 0;
		$('#distribution_list').html("");
		map.clearOverlays();
		var resultCount = loadDistribution();
//		if(firmmarkers.length > 0 && map !=null) 
//		{
//		  	for (var i=0;i<firmmarkers.length;i++) 
//			{
//				var point1 = firmmarkers[i].getLatLng();
//				var point2 = null;
//				
//				if(crazymarker !=null)
//					point2 = crazymarker.getLatLng();
//				else 
//					point2 = point;
//				var distance = getDistance(point1.lat(), point1.lng(), point2.lat(), point2.lng());
//				if(distance <= maxdistance){
//					if(document.getElementById('firm' + i))
//						document.getElementById('firm' + i).style.display = 'block';
//					firmmarkers[i].show();
//					$('#distribution_list').append('<div class="hr1"></div>' + firmdescriptions[i]);
//					resultCount++;
//				}
//				else {
//					if(document.getElementById('firm' + i))
//						document.getElementById('firm' + i).style.display = 'none';			
//					firmmarkers[i].hide();
//				}
//			}
//		}
		//startpos = new GLatLng(lat, lng);
		//map.setCenter(startpos, 6);
//		if(resultCount==0) { 
//			confirmBox('BRAK WYNIKÓW WYSZUKIWANIA\nZWIĘKSZ ZAKRES POSZUKIWAŃ LUB ZMIEŃ LOKALIZACJĘ');
//		}
//		else {
//			var zoom = 6;	
//			if(maxdistance >= 0 && maxdistance < 2){
//				zoom = 13;
//			} 
//			if(maxdistance >= 2 && maxdistance < 3){
//				zoom = 12;
//			} 
//			if(maxdistance >= 3 && maxdistance < 10){
//				zoom = 11;
//			} 
//			if(maxdistance >= 10 && maxdistance < 22){
//				zoom = 10;
//			} 
//			else if(maxdistance >= 22 && maxdistance < 45){
//				zoom = 9;
//			}
//			else if(maxdistance >= 45 && maxdistance < 88){
//				zoom = 8;
//			}
//			else if(maxdistance >= 88){
//				zoom = 7;
//			}
//			map.setCenter(point, zoom);
//		}
	}
	function loadDistribution()
	{
		if(map==null)
		{
			setTimeout('loadDistribution()',300);
			return;
		}
		$.ajax({ 
			url: "../scripts/locations.php", 
			type: "POST",
			dataType: "json",
			data: {lat: point.lat(), lng: point.lng(), range: maxdistance},
			success: function(data){
				$.each(data, function(i, item){
					if(item.lat && item.lng){
						item.location_desc = item.location_desc.replace(/&lt;/g,'<');
		          		item.location_desc = item.location_desc.replace(/&gt;/g,'>');
		          		item.location_desc = item.location_desc.replace(/&amp;/g,'&');
		          		addItemToMap(item.lat,item.lng, item.location_desc);
					}
				});
				if(data.length==0) { 
					confirmBox('BRAK WYNIKÓW WYSZUKIWANIA\nZWIĘKSZ ZAKRES POSZUKIWAŃ LUB ZMIEŃ LOKALIZACJĘ');
				}
				else {
					var zoom = 6;	
					if(maxdistance >= 0 && maxdistance < 2){
						zoom = 13;
					} 
					if(maxdistance >= 2 && maxdistance < 3){
						zoom = 12;
					} 
					if(maxdistance >= 3 && maxdistance < 10){
						zoom = 11;
					} 
					if(maxdistance >= 10 && maxdistance < 22){
						zoom = 10;
					} 
					else if(maxdistance >= 22 && maxdistance < 45){
						zoom = 9;
					}
					else if(maxdistance >= 45 && maxdistance < 88){
						zoom = 8;
					}
					else if(maxdistance >= 88){
						zoom = 7;
					}
					map.setCenter(point, zoom);
				}
			}
		});
	}
//		$.getJSON("{/literal}{$C.access->getPath($C.root)}/scripts/locations.php?lat="+point.lat()+"&lng="+point.lng()+"&range="+maxdistance+"&jsoncallback=?", function(data, textStatus) {  
//			var maxdistance = parseFloat(document.getElementById('distance').value);
//			if(maxdistance > 100) maxdistance = 100;
//			$.each(data.items, function(i,item){
//	          	if(item.lat && item.lng)
//	          	{
//	          		item.location_desc = item.location_desc.replace(/&lt;/g,'<');
//	          		item.location_desc = item.location_desc.replace(/&gt;/g,'>');
//	          		item.location_desc = item.location_desc.replace(/&amp;/g,'&');
//	          		addItemToMap(item.lat,item.lng, item.location_desc);
//	           }
//           });
	function confirmBox(content) {
		var body = $("body");
		var box = $("#confirmBox");
		
		if(box.is(":hidden")) {
			box.show();
			box.css("left", parseInt((body.width() - box.width())/2) +"px");
			box.css("top", parseInt((body.height() - box.height())/2) +"px");
			$("#confirmBoxContent").text(content);
			
			setTimeout("$('#confirmBox').hide()", 5000);
		} else setTimeout("$('#confirmBox').hide()", 3000);
	}
}