/**
 * klasa Gmapy
 *
 */


/* klasa do szukarki Mapy */

if (mapSearchExtend) {

var GMapSearch = Object.extend(Search, {

	dir: [],

	_fillSelectAjax: function(name, element, parameters, clear) 
	{
		var _this = this;

		var ajaxObj = new Ajax.Request('/ajax-form,' + name.toLowerCase() + '-mapa',
		{
			method: 'post',
			parameters: parameters,
			onSuccess: function(transport) {
				var response = transport.responseText.evalJSON();
				
				if (response[name.toLowerCase()] == "")
					return false;

				GMapSearch.dir[name.toLowerCase()] = new Array();
				GMapSearch.dir[name.toLowerCase()] = response['wspolrzedne'];
				// drugie czyszczenie żeby uniknąć wielokrotnego dodania
				clear.each(function(name) {
					Common.Form.clearSelect(_this._elements[name]);
				});
				Common.Form.fillSelect(element, response[name.toLowerCase()]);
			},
			onFailure: function() { 
				alert(Lang.generic_error);
			}
		});

	},

	_callbackTyp: function(event) 
	{
		GMap.dataFilters = Object.extend($('search').serialize(true), {clear: "1"});
		GMap.dataLoaded = false;
		GMap.construct();
	},
	_callbackPanstwo: function(event) 
	{
		var loc = $F(this._elements['panstwo']);
		if (typeof GMapSearch.dir.panstwo[loc] == "undefined")
			return;
		GMap.centerY = GMapSearch.dir.panstwo[loc]['y'];
		GMap.centerX = GMapSearch.dir.panstwo[loc]['x'];
		GMap.centerZoom = GMapSearch.dir.panstwo[loc]['zoom'];
		GMap.setMapCenter();
	},
	_callbackRegion: function(event) 
	{
		var loc = $F(this._elements['region']);
		if (typeof GMapSearch.dir.region[loc] == "undefined")
			return;
		GMap.centerY = GMapSearch.dir.region[loc]['y'];
		GMap.centerX = GMapSearch.dir.region[loc]['x'];
		GMap.centerZoom = GMapSearch.dir.region[loc]['zoom'];
		GMap.setMapCenter();
	},
	_callbackMiejscowosc: function(event) 
	{
		var loc = $F(this._elements['miejscowosc']);
		if (typeof GMapSearch.dir.miejscowosc[loc] == "undefined")
			return;
		if (GMapSearch.dir.miejscowosc[loc]['y'] != 0 && GMapSearch.dir.miejscowosc[loc]['x'] != 0) {
			GMap.centerY = GMapSearch.dir.miejscowosc[loc]['y'];
			GMap.centerX = GMapSearch.dir.miejscowosc[loc]['x'];
			GMap.centerZoom = GMapSearch.dir.miejscowosc[loc]['zoom'];
			GMap.setMapCenter();
		} else {
			GMap.geoShowPin = false;
			var searchTxt = this._elements['miejscowosc'].options[this._elements['miejscowosc'].selectedIndex].text + ', ';
			searchTxt += this._elements['region'].options[this._elements['region'].selectedIndex].text;
			GMap.centerZoom = 12;
			GMap.setGeo(searchTxt);
		}
	},
	_callbackDzielnica: function(event) 
	{
		var loc = $F(this._elements['dzielnica']);
		if (typeof GMapSearch.dir.dzielnica[loc] == "undefined")
			return;
		if (GMapSearch.dir.dzielnica[loc]['y'] != 0 && GMapSearch.dir.dzielnica[loc]['x'] != 0) {
			GMap.centerY = GMapSearch.dir.dzielnica[loc]['y'];
			GMap.centerX = GMapSearch.dir.dzielnica[loc]['x'];
			GMap.centerZoom = GMapSearch.dir.dzielnica[loc]['zoom'];
			GMap.setMapCenter();
		} else {
			GMap.geoShowPin = false;
			var searchTxt = this._elements['dzielnica'].options[this._elements['dzielnica'].selectedIndex].text + ', ';
			searchTxt += this._elements['miejscowosc'].options[this._elements['miejscowosc'].selectedIndex].text + ', ';
			searchTxt += this._elements['region'].options[this._elements['region'].selectedIndex].text;
			GMap.centerZoom = 13;
			GMap.setGeo(searchTxt);
		}
	},
	_callbackPierwotny: function(event) 
	{
		GMap.dataFilters = { rynek: "pierwotny", negocjowalne: "*", panstwo: "1", clear: "1", typ: $F(this._elements['typ']) };
		GMap.dataLoaded = false;
		GMap.construct();
	},
	_callbackWtorny: function(event) 
	{
		GMap.dataFilters = { rynek: "wtorny", negocjowalne: "*", panstwo: "1", clear: "1", typ: $F(this._elements['typ']) };
		GMap.dataLoaded = false;
		GMap.construct();
	},
	_callbackNegocjuj: function(event) 
	{
		GMap.dataFilters = { rynek: "*", negocjowalne: "1", panstwo: "1", clear: "1", typ: $F(this._elements['typ']) };
		GMap.dataLoaded = false;
		GMap.construct();
	},
	_callbackKomercyjne: function(event) 
	{
		GMap.dataFilters = { negocjowalne: "*", panstwo: "1", clear: "1", typ: $F(this._elements['typ']) };
		GMap.dataLoaded = false;
		GMap.construct();
	},
	_callbackZagraniczne: function(event) 
	{
		GMap.dataFilters = { negocjowalne: "*", rynek: "pierwotny", panstwo: "_1", clear: "1", typ: $F(this._elements['typ']) };
		GMap.dataLoaded = false;
		GMap.construct();
	},
	_callbackPrzetargi: function(event) 
	{
		GMap.dataFilters = { przetarg: "1", rynek: "*", negocjowalne: "*", panstwo: "1", clear: "1", typ: $F(this._elements['typ']) };
		GMap.dataLoaded = false;
		GMap.construct();
	},
	_callbackSetupObservers: function() 
	{

		Event.observe(this._elements['submit'], 'click', function(event) {
			GMap.dataFilters = Object.extend($('search').serialize(true), {clear: "1"});
			GMap.dataLoaded = false;
			GMap.construct();
			pageTracker._trackPageview('/mapa/szukaj');
		});
	},

	/**
	 * Wysyla przegladarke na liste ofert z koordynat mapy
	 * 
	 */ 
	submitFormMap: function() 
	{
		GMap.getMapCoordinate();
		GMap.getPOIParam = false;	
		var ajaxObj = new Ajax.Request('/mapa,ajax-user-data',
		{
			method: 'post',
			parameters: Object.extend(GMap.dataFilters, GMap.mapCurrentCoordinate),
			onSuccess: function(transport) {
				try {
					pageTracker._trackPageview('/mapa/lista_ofert_mapy');
				} catch(e) {
					return true;
				}
				if(transport.responseText);
					document.location.href = "/oferty,szukaj";
			},
			onFailure: function() { 
				alert(Lang.generic_error);
			}
		});
	}
	
});

}

/* Podstawowe zmienne mapy */
var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(30, 30);
baseIcon.shadowSize = new GSize(50, 30);
baseIcon.iconAnchor = new GPoint(15, 30);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

/* Mała ikona */
var smallIcon = new GIcon();
smallIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
smallIcon.iconSize = new GSize(16, 16);
smallIcon.shadowSize = new GSize(30, 16);
smallIcon.iconAnchor = new GPoint(1, 1);
smallIcon.infoWindowAnchor = new GPoint(1, 1);
smallIcon.infoShadowAnchor = new GPoint(8, 16);

/* Bardzo mała ikona */
var verySmallIcon = new GIcon();
verySmallIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
verySmallIcon.iconSize = new GSize(12, 12);
verySmallIcon.shadowSize = new GSize(15, 15);
verySmallIcon.iconAnchor = new GPoint(1, 1);
verySmallIcon.infoWindowAnchor = new GPoint(1, 1);
verySmallIcon.infoShadowAnchor = new GPoint(8, 12);

/* ikony typów */
var iconArray = [];
iconArray["apartamenty"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/apartamenty.png", null, "http://www.google.com/mapfiles/shadow50.png");
iconArray["mieszkania"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/mieszkania.png", null, "http://www.google.com/mapfiles/shadow50.png");
iconArray["lofty"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/lofty.png", null, "http://www.google.com/mapfiles/shadow50.png");
iconArray["biura"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/biura.png", null, "http://www.google.com/mapfiles/shadow50.png");
iconArray["handel"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/handlowe.png", null, "http://www.google.com/mapfiles/shadow50.png");
iconArray["magazyny"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/magazyny.png", null, "http://www.google.com/mapfiles/shadow50.png");
iconArray["domy"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/domy.png", null, "http://www.google.com/mapfiles/shadow50.png");
iconArray["dzialki"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/inwestycje.png", null, "http://www.google.com/mapfiles/shadow50.png");
iconArray["oddzial"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/oddzial.png", null, "http://www.google.com/mapfiles/shadow50.png");
iconArray["klient"] = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/klient.png", null, "http://www.google.com/mapfiles/shadow50.png");

var grupIcon = new GIcon(baseIcon, "http://tabelaofert.pl/images/to/map/grupa.png", null, "http://www.google.com/mapfiles/shadow50.png");
var pushpin = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal5/icon14.png", null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
var panoramioIcon = new GIcon(verySmallIcon, "http://tabelaofert.pl/images/to/map/panoramio.gif", null, "http://www.google.com/mapfiles/shadow50.png");

/**
 * Klasa podstawowa Mapy
 *
 */
var GMap = {
	markersArray : [],
	//_poiArray : [],
	panoramioArray : [],
	mapRect : [],
	mapDiv : "mapa_main",
	poiDiv : "gmap_poi_div",
	lbDiv : "lb_inw",
	centerY : 52,
	centerX : 19,
	centerZoom : 6,
	geoShowPin : true,
	geoOutDiv : false,
	geoLastSearch : false,
	geoMarker : false,
	setCenter : true,
	mapBounds : true,
	ajaxUrl : "/mapa,ajax",
	ajaxFormat : "/mapa,ajax-format",
	ajaxPOI : "/mapa,ajax-poi",
	getPOIParam : true,
	centerYPOI : 52,
	centerXPOI : 19,
	dataLoaded : false,
	// dataJson : { json z danymi} - nie definiowac tutaj!
	googleSearch : false,
	gearth : true,
	constructGetPanoramio : false,
	mapControl : false,
	searchOptions : { resultList : G_GOOGLEBAR_RESULT_LIST_SUPPRESS },
	mapTypes: [G_NORMAL_MAP, G_HYBRID_MAP, G_SATELLITE_MAP, G_PHYSICAL_MAP, G_SATELLITE_3D_MAP],
	options: { control: true, wheelZoom: true, observers: true },
	
	/**
	 * Metoda budująca mapę google
	 * @return object
	 */
	construct : function() 
	{
		if (GBrowserIsCompatible() && typeof this.map == "undefined" && $(this.mapDiv)) {
			this.map = new GMap2($(this.mapDiv), {googleBarOptions : this.searchOptions});
			this.geo = new GClientGeocoder();
			this.clusterer = new Clusterer(this.map);
			this.boundsObj = new GLatLngBounds();

			for (var i = 0; i < this.mapTypes.length; i++) {
				this.map.addMapType(this.mapTypes[i]);
			}
			if (this.options.observers) {
				this._setupObservers();
			}
/*	Nie wywalać bo ten problem nie jest jescze do końca rozwiązany [LW]
			if (this.options.control) {
				this.map.addControl(new GLargeMapControl());
				this.map.addControl(new GScaleControl());
				this.overControl = new GOverviewMapControl();
				this.overControl.setMapType(G_NORMAL_MAP);
				this.map.addControl(this.overControl);
				this.mapControl = true;
			} else {
				this.map.addControl(new GSmallZoomControl());
				this.mapControl = false;
			}
*/			
			if(this.options.wheelZoom) {
				this.map.enableScrollWheelZoom();
			}
			if (this.googleSearch) {
				this.map.enableGoogleBar();
			}
			if (this.setCenter) {
				this.setMapCenter();
			}

			if (!this.dataLoaded) {
				this.getData();
			} else {
				if (typeof this.dataJson != 'undefined') {
					this._processMarkers(this.dataJson);
				}
			}

			if (Object.isArray(this.catPOIarray) && Object.isElement($(this.poiDiv))) {
				this.fillPOIlist($(this.poiDiv));
			}
			if (Object.isArray(this.geoArrayElements)) {
				this._setupGeoSelect();
				this._setupGeoElement();
			}
			
		} else if(typeof this.map != "undefined") {
			this.mapResize();
			this.setMapCenter();
			if (!this.dataLoaded) {
				this.getData();
			}
						
		} else {
			if ($(this.mapDiv)) {
				var txtDiv = document.createElement("div");
				txtDiv.style.position = "absolute";
				txtDiv.style.top = "180px";
				txtDiv.style.width = "800px";
				txtDiv.style.textAlign = "center";
				txtDiv.innerHTML = "Błąd! Nie mogę uruchomić mapy";
				$(this.mapDiv).style.position = "relative";
				$(this.mapDiv).insert(txtDiv, { position: content });
			} else {
				alert("Błąd! Nie mogę uruchomić mapy");
			}
		}
	},
	
	/**
	 * 
	 * @param {Object} instance
	 */
	_satelliteMapOptions:	{
		state:	G_HYBRID_MAP,
		subMenuOptions: {
			etykieta: 'pokaż etykiety',
			left: '508px',
			top: '0px',
			type: 'map',
			display: 'block'
		}
	},
	_setupGeoElement : function()
	{
		if (($('moje_oferty_x').value != "" || $('moje_oferty_x').value != 0) && ($('moje_oferty_y').value != "" || $('moje_oferty_y').value != 0)) {
			this.geoMarker = this._generateGeoMarker(new GLatLng($('moje_oferty_y').value, $('moje_oferty_x').value), "marker");
			this.map.addOverlay(GMap.geoMarker);
			GMap.centerY = $('moje_oferty_y').value;
			GMap.centerX = $('moje_oferty_x').value;
			GMap.setMapCenter();
			GEvent.trigger(GMap.geoMarker, "dragend");
			var mapObj = GMap.map;
			GEvent.addListener(mapObj, "click", function(overlay, latlng, overlaylatlng) {
				GMap.geoMarker.setLatLng(latlng);
				GEvent.trigger(GMap.geoMarker, "dragend");
			});
		}
	},
	_setupGeoSelect : function() 
	{
		for (i = 0; i < this.geoArrayElements.length; i++) {
				Event.observe($(this.geoArrayElements[i]), 'change', function(event){
					var element = Event.findElement(event);
					var val = element.options[element.selectedIndex].text;
					
					// *_id dla moje-oferty
					switch (element.name) {
						case 'region':
						case 'region_id':
							GMap.setGeo('polska, ' + val, { zoom: 8, moveMarker: true, geoShowPin: true});
							break
						case 'powiat':
						case 'powiat_id':
							region = $(GMap.geoArrayElements[0]).options[$(GMap.geoArrayElements[0]).selectedIndex].text;
							var text = 'polska, ' + region + ', ' + val;
							//alert(text);
							GMap.setGeo(text, { zoom: 10, moveMarker: true, geoShowPin: true});
							break
						case 'gmina':
						case 'gmina_id':
							region = $(GMap.geoArrayElements[0]).options[$(GMap.geoArrayElements[0]).selectedIndex].text;
							powiat = $(GMap.geoArrayElements[1]).options[$(GMap.geoArrayElements[1]).selectedIndex].text;
							var text = 'polska, ' + region + ', ' + powiat + ', ' + val;
							GMap.setGeo(text, { zoom: 12, moveMarker: true, geoShowPin: true});
							break
						case 'miejscowosc':
						case 'miejscowosc_id':
							region = $(GMap.geoArrayElements[0]).options[$(GMap.geoArrayElements[0]).selectedIndex].text;
							powiat = $(GMap.geoArrayElements[1]).options[$(GMap.geoArrayElements[1]).selectedIndex].text;
							gmina = $(GMap.geoArrayElements[2]).options[$(GMap.geoArrayElements[2]).selectedIndex].text;
							var text = 'polska, ' + region + ', ' + powiat + ', ' + gmina + ', ' + val;
							//alert(text);
							GMap.setGeo(text, { zoom: 14, moveMarker: true, geoShowPin: true});
							break
					}
				});		
		}
		
		
		
	},
	/**
	 * Dodaje obserwery na zakładki typów mapy
	 * 
	 */
	_setupObservers : function() 
	{
		if (Object.isElement($('mapa_earth_tab')) && this.mapTypes.indexOf(G_SATELLITE_3D_MAP) != -1) {
			Event.observe($('mapa_earth_tab'), 'click', function(event){  
				if (Object.isElement($('mapa_satellite_submenu')))
					$('mapa_satellite_submenu').style.display = 'none';
				Common.highlightTab(Event.findElement(event), 'msz_sel');
				GMap.setMapaType(G_SATELLITE_3D_MAP);  
				if (!Object.isElement(GMap.GEinstance))
					GMap.map.getEarthInstance(GMap._earthCallback);
				if (GMap.mapControl) {
					GMap.map.removeControl(new GScaleControl());
					GMap.overControl.hide();
				}
				try {
					pageTracker._trackPageview('/mapa/typ_mapy/earth');
				} catch(e) {
					return true;
				}
			});
		}
		if (Object.isElement($('mapa_map_tab')) && this.mapTypes.indexOf(G_NORMAL_MAP) != -1) {
			Event.observe($('mapa_map_tab'), 'click', function(event){
				if (Object.isElement($('mapa_satellite_submenu')))
					$('mapa_satellite_submenu').style.display = 'none';
				Common.highlightTab(Event.findElement(event), 'msz_sel');
				GMap.setMapaType(G_NORMAL_MAP);
				if (!GMap.mapControl) {
					GMap.map.addControl(new GScaleControl());
					GMap.overControl.show();
				}
				try {
					pageTracker._trackPageview('/mapa/typ_mapy/normalna');
				} catch(e) {
					return true;
				}
			});
		}
		if (Object.isElement($('mapa_terrain_tab')) && this.mapTypes.indexOf(G_PHYSICAL_MAP) != -1) {
			Event.observe($('mapa_terrain_tab'), 'click', function(event){
				if (Object.isElement($('mapa_satellite_submenu')))
					$('mapa_satellite_submenu').style.display = 'none';
				Common.highlightTab(Event.findElement(event), 'msz_sel');
				GMap.setMapaType(G_PHYSICAL_MAP);
				if (!GMap.mapControl) {
					GMap.map.addControl(new GScaleControl());
					GMap.overControl.show();
				}
				try {
					pageTracker._trackPageview('/mapa/typ_mapy/terenowa');
				} catch(e) {
					return true;
				}
			});
		}
		if (Object.isElement($('mapa_satellite_tab')) && (this.mapTypes.indexOf(G_HYBRID_MAP) != -1 || this.mapTypes.indexOf(G_SATELLITE_MAP))) {
			Event.observe($('mapa_satellite_tab'), 'click', function(event){
			
				if (!Object.isElement($('mapa_satellite_submenu'))) {
				
					var options = GMap._satelliteMapOptions.subMenuOptions;
					
					var container = document.createElement("div");
					container.id = "mapa_satellite_submenu";
					container.innerHTML = '<input type="checkbox" id="mapa_satellite_type_checkbox" style="vertical-align: middle;" checked="checked" /> <label for="satelliteTypeCheckBox">' + options.etykieta + '</label>';
					container.className = 'GsubMenu';
					container.style.left = options.left;
					container.style.top = options.top;
					container.style.display = options.display;
					GMap.map.getContainer().appendChild(container);
					
					Event.observe($('mapa_satellite_type_checkbox'), 'click', function(event){
						if (!Event.findElement(event).checked) {
							GMap.setMapaType(G_SATELLITE_MAP);
							GMap._satelliteMapOptions.state = G_SATELLITE_MAP;
						}
						else {
							GMap.setMapaType(G_HYBRID_MAP);
							GMap._satelliteMapOptions.state = G_HYBRID_MAP;
						}
					});
				} else {
					$('mapa_satellite_submenu').style.display = 'block';
				}
				Common.highlightTab(Event.findElement(event), 'msz_sel');
				GMap.setMapaType(GMap._satelliteMapOptions.state);
				if (!GMap.mapControl) {
					GMap.map.addControl(new GScaleControl());
					GMap.overControl.show();
				}
				try {
					pageTracker._trackPageview('/mapa/typ_mapy/satelitarna');
				} catch(e) {
					return true;
				}
			});
		}
		
	},
	
	/**
	 * Instancja obslugi GEarth Pluginu
	 */
	_earthCallback : function(instance) 
	{
	
		try {
			GMap.GEinstance = instance;
    		GMap.GEinstance.getWindow().setVisibility(true);
    		GMap.GEinstance.getNavigationControl().setVisibility(GMap.GEinstance.VISIBILITY_AUTO);
		} catch(e) {
			return false;//alert(e.toString());
		}
    		
	},
	
	/**
	 * przepisuje mapę przy zmiane rozdzielczości
	 * 
	 */
	mapResize : function() 
	{
		this.map.checkResize();
	},
	
	/**
	 * ustawia typ mapy
	 * @param {String} type GMapType
	 * 
	 */
	setMapaType : function(type) 
	{
		this.map.setMapType(type);
	},
	
	/**
	 * Wypełnia DIVa listą głównych kategorii POI
	 * @param {Object} obj
	 */
	fillPOIlist : function(obj) 
	{
		obj.innerHTML += "<ul>"; 
		for ( var i = 0; i < this.catPOIarray.length; i++ ) {
			obj.innerHTML += "<li><input type='checkbox' value='" + this.catPOIarray[i]['key'] + "' name='kategoria' id='" + this.catPOIarray[i]['key'] + "' checked onchange='GMap.getPOIData();' style='vertical-align: middle;' />&nbsp;<label for='" + this.catPOIarray[i]['key'] + "'>&nbsp;<img src='" + iconPOI['LANG_' + this.catPOIarray[i]['key']].image + "' alt='" + this.catPOIarray[i]['val'] + "' width='16' height='16' style='vertical-align: middle; float: none;' /> " + this.catPOIarray[i]['val'] + "</label> </li>";
		}
		obj.innerHTML += "</ul>";
	},
	
	/**
	 * Buduje listę fitrów do pobrania POI
	 */
	checkPOIfilters : function() 
	{
		array = [];
		if ($(this.poiDiv)) {
			this.filtersPOI = "";
			var itemList = $(this.poiDiv).getElementsByTagName("input");
			for (var i = 0; i < itemList.length; i++) {
				if (itemList[i].checked) {
					array[i] = itemList[i].value;
				}
			}	
		}
		return array;
	},
		
	/**
	 * Ustawia dane koordynacyjne mapy, wpolrzedne rogow mapy
	 */
	getMapCoordinate : function() 
	{
		var bounds = this.map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var center = bounds.getCenter(); 
		this.mapCurrentCoordinate = {
			x1: southWest.lng().toFixed(3),
			y1: southWest.lat().toFixed(3),
			x2: northEast.lng().toFixed(3),
			y2: northEast.lat().toFixed(3),
			centerx: center.lng().toFixed(8),
			centery: center.lat().toFixed(8),
			zoom: this.map.getBoundsZoomLevel(bounds)
		};
	},
	
	/**
	 * Wczytuje wybrany obszar mapy
	 * @param {Object} obj
	 */
	getBounds : function(obj) 
	{
		var southWestCorner = obj.boundsObj.getSouthWest();
		var northEastCorner = obj.boundsObj.getNorthEast();
		var centerPoint = obj.boundsObj.getCenter();
		obj.centerX = centerPoint.lng();
		obj.centerY = centerPoint.lat();
		if (obj.boundsObj.isEmpty()) {
			alert("Brak danych, spróbuj zmienić kryteria w wyszukiwarce!");
		} else {
			var boundsPoint = obj.boundsObj.toSpan();
			if (boundsPoint.lat() == 0 && boundsPoint.lng() == 0) {
				obj.centerZoom = 14;
			}
			else if (obj.map.getBoundsZoomLevel(obj.boundsObj) > 11) {
				obj.centerZoom = 11;
			} else {
				obj.centerZoom = obj.map.getBoundsZoomLevel(obj.boundsObj);
			}
		obj.mapRect = { x1: parseFloat(southWestCorner.lng().toFixed(3)), y1: parseFloat(southWestCorner.lat().toFixed(3)), x2: parseFloat(northEastCorner.lng().toFixed(3)), y2: parseFloat(northEastCorner.lat().toFixed(3)), zoom: obj.centerZoom};
		obj.setMapCenter();
		}
	},
	
	/**
	 * Geokoduje szukany string i ustawia na wyszukiwanie mapę
	 * @param {String} search
	 */
	
	geoOptions : {
			zoom: 15,
			moveMarker: false,
			geoShowPin: false
	},
	
	setGeo : function(search, options) 
	{
		this.geoOptions = Object.extend(this.geoOptions, options);
		
		if (this.geoShowPin != this.geoOptions.geoShowPin) { this.geoOptions.geoShowPin = this.geoShowPin; };			
			
		if (typeof this.geo == "undefined") {
			this.setCenter = false;
			this.construct;
		}
		
		this.geo.getLocations(search, function(result) {
			if (result.Status.code == G_GEO_SUCCESS) {
				GMap.geoLastSearch = search;

				if (result.Placemark.length > 1) {
					if (GMap.geoOutDiv && $(geoOutDiv)) {
						if (!$('placeSelect')) {
							var placeSelect = new document.createElement("select");
							placeSelect.id = 'placeSelect';
						} else {
							var placeSelect = $('placeSelect');
							placeSelect.length = 0;
						}
						for (var i = 0; i < result.Placemark.length; i++) {
							var p = result.Placemark[i].Point.coordinates;
							placeSelect.options[i] = new Option(result.Placemark[i].address, result.Placemark[i].address);
						}
						$(geoOutDiv).appendChild(placeSelect);
					} else {
						alert("Zbyt duża ilość wyników");
					}
				} else {
					var p = result.Placemark[0].Point.coordinates;
					GMap.centerY = p[1];
					GMap.centerX = p[0];
					GMap.centerZoom = GMap.geoOptions.zoom;
					
					if (GMap.geoOptions.geoShowPin) {
						if (!GMap.geoMarker) {
							if (GMap.geoOptions.moveMarker) {
								GMap.geoMarker = GMap._generateGeoMarker(new GLatLng(p[1], p[0]), search);
								GMap.map.addOverlay(GMap.geoMarker);
								GEvent.trigger(GMap.geoMarker, "dragend");
							} else {
								GMap.geoMarker = new GMarker(new GLatLng(p[1], p[0]), {
									"icon": pushpin,
									"id": "punkt",
									"title": search
								});
								GMap.map.addOverlay(GMap.geoMarker);
							}
						} else {
							GMap.geoMarker.setLatLng(new GLatLng(p[1],p[0]));
							if (GMap.geoOptions.moveMarker) {
								GEvent.trigger(GMap.geoMarker, "dragend");
							}
						}
					}
					GMap.setMapCenter();
				}
			} else {
				alert("Nie udało się pobrać lokacji");
			}
		});
	},
	
	_generateGeoMarker: function(point, text) 
	{
		
		var marker = new GMarker(point, {
			"icon": pushpin,
			"id" : "point",
			"title" : text,
			"draggable" : true
		});
		
		GEvent.addListener(marker, "dragend", function() {
			var wspolrzedne = marker.getLatLng();
			if (Object.isElement($('moje_oferty_x')) && Object.isElement($('moje_oferty_y'))) {
				$('moje_oferty_x').value = wspolrzedne.lng();
				$('moje_oferty_y').value = wspolrzedne.lat();
				$('moje_oferty_map_zoom').value = GMap.map.getZoom();
			} else {
				alert("X:" + wspolrzedne.lat() + " Y:" + wspolrzedne.lng());
			}

			// Wyświetlenie informacyjnych współrzędnych z dokładnościa 4 miejsc po przecinku 
			if (Object.isElement($('moje_oferty_x_info')) && Object.isElement($('moje_oferty_y_info'))) {
				$('moje_oferty_x_info').innerHTML = Math.round(wspolrzedne.lng() * 10000) / 10000;
				$('moje_oferty_y_info').innerHTML = Math.round(wspolrzedne.lat() * 10000) / 10000;
			}
		});
		return marker;
	},
	
	/**
	 * Centruje mapę zgodnie z ustawionymi parametrami
	 * this.centerY, this.centerX, this.centerZoom
	 */
	setMapCenter : function() 
	{
		this.map.setCenter(new GLatLng(this.centerY, this.centerX), this.centerZoom);
	},

	/**
	 * Pobiera dane inwestycji Ajaxem
	 */
	getData : function() 
	{                       
		try {
			this.loadingContainer = Common.Loader.open();
			var ajaxObj = new Ajax.Request(this.ajaxUrl,
				{
					method:'post',
					parameters : GMap.dataFilters,
					onSuccess: function(transport){
						try {
							var response = transport.responseText.evalJSON(true);
							GMap._processMarkers(response);
							// post map generated checks
							if (GMap.loadingContainer) {
								GMap.loadingContainer.destroy();
							}
						}
						catch(e) {
							GMap.loadingContainer.destroy();
							return false;
						} 
					}
				}
			);
		}
		catch(e) {
			GDownloadUrl(this.ajaxUrl, this.processMarkers, this.postParams);
		}
	},

	/**
	 * Wyszukanie w tablicy i otwarcie markera o zadanym ID
	 * 
	 */
	clickMarker: function(options) 
	{
		
		if (Object.isArray(GMap.markersArray)) {
			for (var i = 0; i < GMap.markersArray.length; i++) {
				if ( parseInt(GMap.markersArray[i].lokalID) == parseInt(options.lokalID) || parseInt(GMap.markersArray[i].inwID) == parseInt(options.inwID) || parseInt(GMap.markersArray[i].klientID) == parseInt(options.klientId)) {
					var LatLng = GMap.markersArray[i].getLatLng();
					if (GMap.map.getZoom != 13)
						GMap.map.setZoom(13);
					GMap.map.panTo(LatLng);
					break;
				}				
			}
		}
	},

	/**
	 * Przetwarza zwrot z AJAXa celem budowy markerów
	 * @param {Object} doc
	 */
	_processMarkers : function(jsonData) 
	{              
		if (typeof GMap.markersArray[0] == "object") {
			for (var i = 0; i < GMap.markersArray.length; i++) {
				GMap.clusterer.RemoveMarker(GMap.markersArray[i]);
			}
			GMap.map.clearOverlays();
		}
		if (!GMap.boundsObj.isEmpty()) {
			GMap.boundsObj = new GLatLngBounds();
		}
		GMap.markersArrayCount = jsonData.markers.length;
		for (var i = 0; i < jsonData.markers.length; i++) {
			var dane = jsonData.markers[i];
			var point = new GLatLng(parseFloat(dane.lng), parseFloat(dane.lat));
			GMap.markersArray[i] = GMap._generateMarker(point, dane);
			GMap.clusterer.AddMarker(GMap.markersArray[i], dane.cluLabel, i);
			if (GMap.mapBounds) {
				GMap.boundsObj.extend(point);
			}			
		}
		GMap.dataLoaded = true;
		
		if ($(GMap.lbDiv)) {
			$(GMap.lbDiv).innerHTML = (GMap.markersArray.length - 1);
		}
		if (GMap.mapBounds) {
			GMap.getBounds(GMap);
		}
		
		// załadowanie od razu POI do centrum mapy
		if (!GMap.getPOIParam) {
			GMap.getMapCoordinate();
			GMap.centerXPOI = GMap.mapCurrentCoordinate.centerx;			
			GMap.centerYPOI = GMap.mapCurrentCoordinate.centery;
			GMap.getPOIData();
		}
		
		if (GMap.constructGetPanoramio)
			GMap.getPanoramio();
		
	},

	_colorTools: {
		
		RGB2Color: function (r,g,b) {
	    	return '#' + this.byte2Hex(r) + this.byte2Hex(g) + this.byte2Hex(b);
	  	},
	  	byte2Hex: function (n) {
	  		var nybHexString = "0123456789ABCDEF";
	  		return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
	  	}
	},
	
	_colorIconMaker: function (phase) 
	{
		if (MapIconMaker) {
			if (phase == undefined) phase = 120;
			center = 128;
			width = 127;
			frequency = (Math.PI*2)/GMap.markersArrayCount;
			//frequency = 0.06
			//alert(frequency);
			if (typeof this._colorTools.colorCount == "undefined")
				GMap._colorTools.colorCount = 0
			else
				GMap._colorTools.colorCount++;
			red   = Math.sin(frequency*GMap._colorTools.colorCount+2+phase) * width + center;
			green = Math.sin(frequency*GMap._colorTools.colorCount+0+phase) * width + center;
			blue  = Math.sin(frequency*GMap._colorTools.colorCount+4+phase) * width + center;
			return MapIconMaker.createMarkerIcon({width: 30, height: 30, primaryColor: GMap._colorTools.RGB2Color(red,green,blue)});
		} else {
			return pushpin;
		}
		

	},
	
	/**
	 * Generuje Markera na mapie
	 * @param {Object} point
	 * @param {Object} dataObj
	 * @param {Object} fieldsObj
	 */
	_generateMarker : function(point, dataObj) 
	{
		if (typeof dataObj.icon == "undefined" || dataObj.icon == "rainbow") {
			dataObj.icon = "rainbow"
			iconArray["rainbow"] = GMap._colorIconMaker();
		}
		var marker = new GMarker(point, {icon: iconArray[dataObj.icon], title: dataObj.label, clickable: true, draggable: false } );
		var markerParams = {};
		if (typeof dataObj.inwID != "undefined") {
			marker.inwID = dataObj.inwID;
			markerParams = { inwestycja: dataObj.inwID };

			// Jeżeli dostaliśmy targiID to je przekazujemy.
			if (typeof dataObj.targiID != 'undefined')
				markerParams.targi = dataObj.targiID;
		}
		else if (typeof dataObj.lokalID != "undefined")  {
			marker.lokalID  = dataObj.lokalID;
			markerParams = { oferta: dataObj.lokalID };
		} else {
			marker.klientID = dataObj.klientID;
			markerParams = { oferent: dataObj.klientID };
			if ($('baloon_' + dataObj.klientID)) {
				$('baloon_' + dataObj.klientID).src = iconArray["rainbow"].image;
			}
		}
		if (GMap.ajaxFormat) {
			GEvent.addListener(marker, "click", function() {
	
				markerParams = Object.extend(markerParams);
				
				try {
					marker.openInfoWindowTabsHtml([new GInfoWindowTab('opis', '<div style="background: url(http://tabelaofert.pl/images/to/other/loading.gif) no-repeat center center white; height: 50px; width: 50px;">&nbsp;</div>')]);
					var ajax = new Ajax.Request((GMap.ajaxFormat),
							{
								method: 'post',
								parameters: markerParams,
								onSuccess: function(transport) {
									var response = transport.responseText;
									marker.openInfoWindowTabsHtml([new GInfoWindowTab('opis', response)]);
									if (GMap.getPOIParam && GMap.map.getZoom() > 10) {
										GMap.centerYPOI= dataObj.lng;
										GMap.centerXPOI= dataObj.lat;
										GMap.getPOIData();
									}
								},
								onFailure: function(){
									GMap.map.updateInfoWindow([new GInfoWindowTab('opis','Błąd!, Nie udało się pobrać danych')]);
								}
							}
						);
				} catch(e) {
					if (html_big) {
						marker.openInfoWindowHtml(html_small, { maxContent: html_big, maxTitle: "<b style='text-align: center;'>" + dataObj.label + "</b>"});
					} else {
						marker.openInfoWindowHtml(html_small);
					}			
				}
				
			});
		}
		return marker;
	},


	/**
	 * Pobiera dane punków POI
	 */
	getPOIData : function() 
	{
		try {
			this.loadingContainer = Common.Loader.open();
			ajaxObj = new Ajax.Request(this.ajaxPOI,
				{
					method: 'post',
					parameters : { poiy: GMap.centerYPOI, poix: this.centerXPOI, kategoria_poi: Object.toJSON(GMap.checkPOIfilters())},
					onSuccess: function(transport){
						try {
							var response = transport.responseText.evalJSON(true);
							GMap._processPOIMarkers(response);
							if (GMap.loadingContainer) {
								GMap.loadingContainer.destroy();
							}
						}
						catch(e) {
							GMap.loadingContainer.destroy();
							return false;
						}
					},
					onFailure: function(){ alert('Something went wrong...') }
				}
			);
		}
		catch(e) {	
			GDownloadUrl(this.ajaxPOI + ",poiy," + this.centerYPOI + ',poix,' + this.centerXPOI + this.filtersPOI, this.processPOIMarkers, this.postPOIParams);
		}
	},

	/**
	 * Przetwarza zwrot z AJAXa celem budowy markerów POI
	 * @param {Object} doc
	 */
	_processPOIMarkers : function(jsonData) 
	{
		if (!Object.isUndefined(GMap._poiArray)) {
			for (var i = 0; i < GMap._poiArray.length; i++) {
				GMap.map.removeOverlay(GMap._poiArray[i]);
			}
		}
		GMap._poiArray = new Array();
		for (var i = 0; i < jsonData.markers.length; i++) {
			//alert(jsonData.markers[i].poiNazwa);
			var point = new GLatLng(parseFloat(jsonData.markers[i].poiY), parseFloat(jsonData.markers[i].poiX));
			GMap._poiArray[i] = GMap._generatePOIMarker(point, jsonData.markers[i]);
			GMap.map.addOverlay(GMap._poiArray[i]);
		}
	},
	
	/**
	 * Generuje marker punktu POI
	 * @param {Object} point
	 * @param {Object} dataObj
	 */
	_generatePOIMarker : function(point, dataObj) 
	{
		if (!Object.isUndefined(iconPOI[dataObj.katNazwa])) {
			var markerIcon = iconPOI[dataObj.katNazwa];
		} else {
			var markerIcon = iconPOI[dataObj.katGlowna];
		} 
		var marker = new GMarker(point, { icon: markerIcon, title: dataObj.poiNazwa, clickable: true, draggable: false } );
		var html_small = '<img src="' + markerIcon.image + '" / alt="' + GMap.catPOIarrayDetails[dataObj.katNazwa] + '" style="vertical-align: middle" /> ' + dataObj.poiNazwa + "<br/>" + dataObj.poiUlica + "<br/>" + dataObj.poiKod + " " + dataObj.gmina;
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html_small);
		});
		return marker;
	},

	/**
	 * Pobranie zdjęć z panoramio dla zadanych wpolzędnych pobranych z zakresu mapy
	 *
	 */
	 getPanoramio : function() 
	 {
	 	this.getMapCoordinate();
	 	try {
			ajaxObj = new Ajax.Request('/mapa,ajax-panoramio',
				{
					method: 'post',
					parameters : {
						link: 'http://www.panoramio.com/map/get_panoramas.php',
						minx: this.mapCurrentCoordinate.x1,
						miny: this.mapCurrentCoordinate.y1,
						maxx: this.mapCurrentCoordinate.x2,
						maxy: this.mapCurrentCoordinate.y2
						},
					onSuccess: function(transport){
						try {
							var response = transport.responseText.evalJSON(true);
							GMap._processPanoramioMarkers(response);
						}
						catch(e) {
							return false;
						}
					},
					onFailure: function(){ alert('Something went wrong...') }
				}
			);
		}
		catch(e) {	
			//GDownloadUrl(this.ajaxPOI + ",poiy," + this.centerYPOI + ',poix,' + this.centerXPOI + this.filtersPOI, this.processPOIMarkers, this.postPOIParams);
			alert('Something went wrong...');
		}
	 },
	 
	 _processPanoramioMarkers : function(jsonData) 
	 {
		for (var i = 0; i < GMap.panoramioArray.length; i++) {
			GMap.map.removeOverlay(GMap.panoramioArray[i]);
		}
		GMap.panoramioArray = [];
		for (var i = 0; i < jsonData.photos.length; i++) {
			var point = new GLatLng(parseFloat(jsonData.photos[i].latitude), parseFloat(jsonData.photos[i].longitude));
			GMap.panoramioArray[i] = GMap._generatePanoramioMarker(point, jsonData.photos[i]);
			GMap.map.addOverlay(GMap.panoramioArray[i]);
		}
	},
	
	_generatePanoramioMarker : function(point, dataObj) 
	{
		var marker = new GMarker(point, { icon: panoramioIcon, title: dataObj.photo_title, clickable: true, draggable: false } );
		var html_small = '<div style="width: ' + dataObj.width + 'px; height: ' + (parseInt(dataObj.height)+35) + 'px; text-align: center;">';
		html_small += '<a href="' + dataObj.photo_url + '" target="_new"><img src="' + dataObj.photo_file_url + '" / alt="' + dataObj.photo_title + '" /></a>';
		html_small += '<br /> ' + dataObj.photo_title + ', ' + dataObj.owner_name + '<br /><a href="' + dataObj.photo_url + '" target="_new">&copy; Panoramio</a></div>';
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html_small);
		});
		return marker;
	}
}
