var points = [];
var markers = [];
var gicons=[];
var counter = 0;
var sidebar_html = "";
var marker_html = [];
var map = null;
var element = "map";
var centerLat = 52.300000;
var centerLon = 19.100000;
var zoom = 5;
var sidebar = false;
var getCount = 100;
var startCount = 1;
var userId = 0;
var mm = null;
var region = 0;
var woj = 0;
var kategoria = 0;
var miasto = 0;
var loaded = 0;
var wojewodztwa = new Array();
wojewodztwa[1] = ['Dolnośląskie',51.1339861,16.8841961];
wojewodztwa[2] = ['Kujawsko-Pomorskie',53.1648363,18.4834224];
wojewodztwa[3] = ['Lubelskie',51.2493519,23.1011392];
wojewodztwa[4] = ['Lubuskie',52.2274612,15.2559103];
wojewodztwa[5] = ['Łódzkie',51.4634771,19.1726974];
wojewodztwa[6] = ['Małopolskie',49.7225306,20.2503359];
wojewodztwa[7] = ['Mazowieckie',52.5373228,21.0768288];
wojewodztwa[8] = ['Opolskie',50.8003761,17.937989];
wojewodztwa[9] = ['Podkarpackie',50.0574749,22.0895691];
wojewodztwa[10] = ['Podlaskie',53.0697159,22.9674639];
wojewodztwa[11] = ['Pomorskie',54.2944252,18.1531164];
wojewodztwa[12] = ['Śląskie',50.1716595,19.0219768];
wojewodztwa[13] = ['Świętokrzyskie',50.6261041,20.9406279];
wojewodztwa[14] = ['Warmińsko-Mazurskie',53.8671117,20.702786];
wojewodztwa[15] = ['Wielkopolskie',52.279986,17.3522939];
wojewodztwa[16] = ['Zachodniopomorskie',53.4657891,15.1822581];

function resetMap() {
	alert(counter);
	counter = 0;
	var ObiektSelect = document.forms['pkts'].elements['punkty'];
	for(i = 0; i < ObiektSelect.options.length; i++) {
		ObiektSelect.removeChild( ObiektSelect.options[ i ] );
	}
}

function onLoad() {
	if (GBrowserIsCompatible()) {
		/*		var ObiektSelect = document.forms['pkts'].elements['punkty'];
		for(i = 0; i < ObiektSelect.options.length; i++) {
			ObiektSelect.removeChild( ObiektSelect.options[ i ] );
		}
		
		if(map !== null) {map.clearOverlays(); mm.refresh();}
		points = [];
		markers = [];
		marker_html = [];
		counter = 0;
		zoom = 5; */

		var mapObj = document.getElementById(element);
			if (mapObj != "undefined" && mapObj != null) {
				window.map = new GMap2(document.getElementById(element));
				map.addControl(new GLargeMapControl3D());
				map.addControl(new GMapTypeControl());
				map.removeMapType(G_HYBRID_MAP);
				map.removeMapType(G_SATELLITE_MAP);
//				map.removeMapType(G_NORMAL_MAP);
//				map.addMapType(G_PHYSICAL_MAP);
				
				if (region != 0) {
					var sw = new GLatLng(swLat, swLon);  
					var ne = new GLatLng(neLat, neLon);  
					var bounds = new GLatLngBounds(sw, ne);  
 					map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
				}
				else 
					map.setCenter(new GLatLng(centerLat, centerLon), zoom);
					
					if(sidebar)
					document.getElementById("sidebar_map").innerHTML = "<ul class=\"gmapSidebar\">"+ sidebar_html +"<\/ul>";
			}
			
		mm = new GMarkerManager(map);
		window.loaded = 1;
		setTimeout("getPoints()",1200);
		
//		showAll();
		GEvent.addListener(map, 'moveend', function() {
			startCount = 1;
			getPoints();			
     	});
		
		GEvent.addListener(map, 'resize', function() {
			startCount = 1;
			getPoints();			
     	});
					
	} else {
		alert("Sorry, the Google Maps API is not compatible with this browser.");
	}
//	setTimeout("alert(markers[0].getLatLng())",2000);
	
}

function getBounds() {
	var bds = new Array();
	var bound = map.getBounds();
	bds['swLat'] = bound.getSouthWest().lat();
	bds['swLon'] = bound.getSouthWest().lng();
	bds['neLat'] = bound.getNorthEast().lat();
	bds['neLon'] = bound.getNorthEast().lng();
	return bds;
}

function getPoints() {
	bds = getBounds();
	new Ajax.Request('/ajax/index', {
		method:'get',
		parameters: {getCount: getCount, region: region, startCount: window.startCount, zoom: zoom, swLat: bds['swLat'], swLon: bds['swLon'], neLat: bds['neLat'], neLon: bds['neLon'], woj: woj, kategoria: kategoria, miasto: miasto, rodzaj: rodzaj},
  		requestHeaders: {Accept: 'application/json'},
  		onSuccess: function(transport){
    		var txt = transport.responseText;
			if(txt.isJSON) {
				var jsn = txt.evalJSON(true);
				for (var i=0; i<getCount; i+=1) {
					if(!Object.isUndefined(jsn.element[i])) {						
						var point = new GLatLng(jsn.element[i].lat,jsn.element[i].lon);
						point.objectId = jsn.element[i].objectId;
						point.miasto = jsn.element[i].miasto;
						point.miastoId = jsn.element[i].miastoId;
						point.ulica = jsn.element[i].ulica;
						createMarker(point,"punkt"+jsn.element[i].objectId, jsn.element[i].objectHtml, 0,"", jsn.element[i].categoryZoomVisible, jsn.element[i].kategoria, jsn.element[i].categories, jsn.element[i].miastoId, jsn.element[i].zoomStart);
					} else
						exit;
				}
				window.startCount += 1;
//				if(window.start < 2)
//				mm.refresh();
					getPoints();
			}
  		},
	    onFailure: function(){ alert('Błąd pobrania danych') }

	});
//	checkShowAndHide();
}

function createMarker(point, title, html, n, tooltip, zoom, category, woj, miastoId, zoomStart, zoomEnd) {
	if(n >= 0) { n = -1; }
	var err = 0;
	points.each( function (item) {
		if(item.x == point.x && item.y == point.y)
			err = 1;

		if (item.objectId == point.objectId) {
			err = 1;
		}
	});

	if (err == 0) {
		var marker = new GMarker(point, {'title': tooltip, 'icon': gicons[category]});
		marker.mycategory = category;
		marker.woj = woj;
		marker.miastoId = miastoId;
		if(isArray(html)) { GEvent.addListener(marker, "click", function() { marker.openInfoWindowTabsHtml(html); }); }
		else { GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); }); }
		points[counter] = point;
		markers[counter] = marker;
		marker_html[counter] = html;
		if (sidebar) 
			sidebar_html += '<li class="gmapSidebarItem" id="gmapSidebarItem_' + counter + '"><a href="javascript:click_sidebar(' + counter + ')">' + title + '<\/a><\/li>';
		
		if (zoomStart != undefined || zoomEnd != undefined) 
			mm.addMarker(marker, zoomStart, zoomEnd);
		else
			mm.addMarker(marker, 1);
		
		if($('punkty') !== null || $('punkty') !== undefined) {
		/*	a = document.createElement('option');
			Element.extend(a);
			a.text = point.miasto+', '+point.ulica;
			a.value = counter;
			a.style.color = "#000";
			$('punkty').appendChild(a);*/
			var ObiektSelect = document.forms['pkts'].elements['punkty'];
			a = new Option(point.miasto+', '+point.ulica, counter)
			Element.extend(a);
			a.addClassName('opt'+category);
			ObiektSelect.options[ObiektSelect.options.length] = a;
			
		}
		
		counter++;
			
		return true;
//		alert(markers.length);
	} else
		return false;
}

function isArray(a) {return isObject(a) && a.constructor == Array;}

function isObject(a) {return (a && typeof a == 'object') || isFunction(a);}

function isFunction(a) {return typeof a == 'function';}

function click_sidebar(idx) {
  if(isArray(marker_html[idx])) { markers[idx].openInfoWindowTabsHtml(marker_html[idx]); }
  else { markers[idx].openInfoWindowHtml(marker_html[idx]); }
}

function showInfoWindow(idx,html) {
	map.centerAtLatLng(points[idx]);
	markers[idx].openInfoWindowHtml(html);
}

function checkShowAndHide() {
	
}

function resizeMap() {
	map.checkResize();
}

function showAll() {
		return true;
        tablica.each( function(a, index) {
			if(a === undefined)
				show(index);
			else
				show(a['categoryId']);
		});

}

function hideAll() {
	return true;	
        tablica.each( function(a, index) {
			if(a === undefined)
				hide(index);
			else
				hide(a['categoryId']);
		});
}


function mapshow(category) {
	var ObiektSelect = document.forms['pkts'].elements['punkty'];
	for (var i=0; i<ObiektSelect.options.length;i++) {
		Element.extend(ObiektSelect.options[i]);
		if(!ObiektSelect.options[i].hasClassName('opt'+category)) {ObiektSelect.options[i].disabled = true;}
		else ObiektSelect.options[i].disabled = false;;
	}; 

	for (var i=0; i<markers.length; i++) {
          if (markers[i].mycategory == category) {
		  	markers[i].show();
		  }
		  else {
		  	markers[i].hide();			
		  }
        }
        // == check the checkbox ==
	return false;
}

function mapWojShow(woj) {
	for (var i=0; i<markers.length; i++) {
          if (markers[i].woj == woj || woj == 0) {
		  	markers[i].show();
		  }
		  else {
		  	markers[i].hide();			
		  }
        }
        // == check the checkbox ==
	if(woj != 0)
		map.setCenter(new GLatLng(wojewodztwa[woj][1], wojewodztwa[woj][2]), 8);
	else
		map.setCenter(new GLatLng(centerLat, centerLon), zoom);
	return false;
}

function mapMiastoShow(mst) {
	mst = mst.split(',');
	for (var i=0; i<markers.length; i++) {
          if (markers[i].miastoId == mst[0] || mst[0] == 0) {
		  	markers[i].show();
		  }
		  else {
		  	markers[i].hide();			
		  }
        }
        // == check the checkbox ==
	if(mst[0] != 0)
		map.setCenter(new GLatLng(mst[1], mst[2]), 12);
	else
		map.setCenter(new GLatLng(centerLat, centerLon), zoom);
	return false;
}

function mapClearShow() {
	var ObiektSelect = document.forms['pkts'].elements['punkty'];
	for (var i=0; i<ObiektSelect.options.length;i++) {
		ObiektSelect.options[i].disabled = false;
	};
	for (var i=0; i<markers.length; i++) {
		markers[i].show();
	}
	map.setCenter(new GLatLng(52.300000, 19.100000), 5);
	return false;
}

      // == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
		if (category == 'ha') {
			hideAll();
		}
		else {
			// == clear the checkbox ==
		// == close the info window, in case its open on a marker that we just hid
		
			for (var i = 0; i < markers.length; i++) {
				markers[i].mycategory.each(function(b, index) {
					if (b == category) {
						markers[i].hide();
					} 
				});
				
				markers[i].mycategory.each(function(b, index) {
					if (b != category && $("k" + b).checked == true) {
						markers[i].show();
					}
				});
			}


		}
        map.closeInfoWindow();
}

      // == a checkbox has been clicked ==
function boxclick(box,category) {
	return true;
        if (box.checked) {
		  if(category == 'sa')
		  	showAll();
		  else if(category == 'ha')
		  	hideAll();
		  else	
            show(category);
        } else {
          if(category == 'ha')
		  	hideAll();
		  else	
            hide(category);
        }
        // == rebuild the side bar
        makeSidebar();
      }

function myclick(i) {
        GEvent.trigger(markers[i],"click");
}


      // == rebuilds the sidebar to match the markers currently displayed ==
      function makeSidebar() {
/*        var html = "";
        for (var i=0; i<markers.length; i++) {
          if (!markers[i].isHidden()) {
            html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
          }
        }
        document.getElementById("side_bar").innerHTML = html;*/
      }
