var http_request = false;
var id;
var p;
var map;
var geopoint;
var geocoder;
var zoomlevel;
var clicked = false;
var dane;
var points = new Array();
var out;
var icon;
var ulica_icon;
var addresspoint;
var isSetLocation;
var noupdate = true;
var percent = 0;
var type;

function load() {	
    map = new GMap2(document.getElementById("map"));
    //map.addControl(new GHierarchicalMapTypeControl());
    // add the Earth map type      
    //map.addMapType(G_SATELLITE_3D_MAP);
    // obtain a pointer to the Google Earth instance attached to your map.
    //map.getEarthInstance(getEarthInstanceCB);
    
    var mt = map.getMapTypes();
	    for (var i=0; i<mt.length; i++) {
		    if (mt[i].getName() == 'Hybrid') {
			    mt[i].getName = function() { return "Hybrydowa";}
			}
			if (mt[i].getName() == 'Map') {
				mt[i].getName = function() { return "Mapa";}
			}
			if (mt[i].getName() == 'Satellite') {
				mt[i].getName = function() { return "Satelitarna";}
			} 
		}
 	map.enableContinuousZoom();
	//map.enableScrollWheelZoom();
	map.disableScrollWheelZoom();
    map.addControl(new GLargeMapControl());
    map.addControl(new GScaleControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GOverviewMapControl());
    map.setCenter(new GLatLng(52,19), 6);
    geocoder = new GClientGeocoder();//new google.maps.Geocoder();//
    document.getElementById('q').value='';
    stopLoader(); 	
    
    if (window.addEventListener)
        /** DOMMouseScroll is for mozilla. */
        window.addEventListener('DOMMouseScroll', wheel, false);
	/** IE/Opera. */
	window.onmousewheel = document.onmousewheel = wheel;
	GEvent.addListener(map, "zoomend", function() {
  		updateLocation();
	});
	GEvent.addListener(map, "moveend", function() {
  		updateLocation();
	});
	GEvent.addListener(map, "click", function(overlay,  latlng,  overlaylatlng) {
  		//alert("overlay:"+overlay);
  		//alert("latlng:"+latlng); 
  		//alert("overlaylatlng:"+overlaylatlng);
  		//noupdate = false;
	});
	GEvent.addListener(map, "dragstart", function() {
		map.getInfoWindow().hide();
	});
	var loadingProgressBar = document.createElement('div');
	loadingProgressBar.id = 'loadingProgressBar';
	loadingProgressBar.style.border = "3px solid #709762";
	loadingProgressBar.style.backgroundColor = "#fff";
	loadingProgressBar.style.color = "#709762";
	loadingProgressBar.style.fontSize = "15px";
	loadingProgressBar.style.fontWeight = "bold";
	loadingProgressBar.style.position = "absolute";
	loadingProgressBar.style.left = "30%";
	loadingProgressBar.style.top = "40%";
	loadingProgressBar.style.display = "none";
	loadingProgressBar.style.textAlign = "center";
	loadingProgressBar.style.padding = "10px";
	document.getElementById("map").appendChild(loadingProgressBar);
}
var ge;
    function getEarthInstanceCB(pluginInstance) {
      ge = pluginInstance;
      
      // you can now manipulate ge using the full Google Earth API.
    }

function wheel(event){
        var delta = 0;
        if (!event) /* For IE. */
                event = window.event;
        if (event.wheelDelta) { /* IE/Opera. */
                delta = event.wheelDelta/120;
                /** In Opera 9, delta differs in sign as compared to IE.
                 */
                if (window.opera)
                        delta = -delta;
        } else if (event.detail) { /** Mozilla case. */
                /** In Mozilla, sign of delta is different than in IE.
                 * Also, delta is multiple of 3.
                 */
                delta = -event.detail/3;
        }
        /** If delta is nonzero, handle it.
         * Basically, delta is now positive if wheel was scrolled up,
         * and negative, if wheel was scrolled down.
         */

	    isSetLocation = true;
       	
        /** Prevent default actions caused by mouse wheel.
         * That might be ugly, but we handle scrolls somehow
         * anyway, so don't bother here..
         */
        if (event.preventDefault) event.preventDefault();
		event.returnValue = false;
}

   
function createMarker(point, id, icon) {
	var marker = new GMarker(point, icon);
    p = marker.getPoint().toUrlValue(); 
    geopoint = marker.getPoint();	  	
    GEvent.addListener(marker, "click", function() {
        p = marker.getPoint().toUrlValue();
		geopoint = marker.getPoint();			
		getPointData(id, marker);
		stopLoader();
		clicked = true;
	});    
   return marker;
} 

function createPin(point, id) {	 
	//map.clearOverlays(); 
	pinicon  = new GIcon(G_DEFAULT_ICON, "http://google.webassist.com/google/markers/pushpin/cabosunset.png");
	var pinicon = new GIcon();
    var markerStyle = 'Push-Pin';
    var markerColor = 'Tahiti Sea';
    pinicon.image = 'http://google.webassist.com/google/markers/pushpin/tahitisea.png';
    pinicon.shadow = 'http://google.webassist.com/google/markers/pushpin/shadow.png';
    pinicon.iconSize = new GSize(40,41);
    pinicon.shadowSize = new GSize(40,41);
    pinicon.iconAnchor = new GPoint(7,38);
    pinicon.infoWindowAnchor = new GPoint(26,4);
    pinicon.printImage = 'http://google.webassist.com/google/markers/pushpin/tahitisea.gif';
    pinicon.mozPrintImage = 'http://google.webassist.com/google/markers/pushpin/tahitisea_mozprint.png';
    pinicon.printShadow = 'http://google.webassist.com/google/markers/pushpin/shadow.gif';
    pinicon.transparent = 'http://google.webassist.com/google/markers/pushpin/tahitisea_transparent.png';	
	var marker = new GMarker(point, pinicon);
    p = marker.getPoint().toUrlValue(); 
    geopoint = marker.getPoint();	  	
    return marker;
}

function addAddressToMap(response) {
    if (!response || response.Status.code != 200) {
        map.setCenter(geopoint, zoomlevel , G_NORMAL_MAP);
    } else {
        place = response.Placemark[0];
        addresspoint = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		map.setCenter(addresspoint, zoomlevel , G_NORMAL_MAP);
        map.addOverlay(marker=createPin(addresspoint));   
	}
}
	
function showLocation(lokalization) {
  if(lokalization=='gdziekolwiek' || lokalization=='--------------' || lokalization=='polska' || lokalization=='Polska') {
        lokalization='Polska'; 
        zoomlevel = 6;
   }
  isSetLocation = true;
  geocoder.getLocations(lokalization.replace('Lublin', 'Lubelskie Lublin') , addAddressToMap);  
  /*
  geocoder = new GClientGeocoder();//new google.maps.Geocoder();
  geocoder.geocode(lokalization.replace('Lublin', 'Lubelskie Lublin') , addAddressToMap); */  		      
}

function ShowLocationByInputText(name) {
	noupdate = true;
  	zoomlevel = 15;
	//map.clearOverlays(); 
	showLocation(document.getElementById(name).value);
}	

function showLocationByCityList(cityListId) {
    noupdate = true;
	zoomlevel = 10;
	var objcity = document.getElementById(cityListId);
	//map.clearOverlays(); 
	showLocation(objcity.options[objcity.selectedIndex].text);
	document.getElementById('q').value='';
}

function showLocationBySuburbList(cityListId, suburbListId) {
    noupdate = true;
 	zoomlevel = 14;
	var objcity = document.getElementById(cityListId);
	var objsuburb = document.getElementById(suburbListId);
	//map.clearOverlays(); 
	showLocation(objcity.options[objcity.selectedIndex].text+' ('+objsuburb.options[objsuburb.selectedIndex].text+')');
	document.getElementById('q').value='';
}

function updateLocation() {
	if(!noupdate) {
		if(map.getInfoWindow().isHidden()){
			clicked = false;
			getMarkerPoints();
		}
	}
}

var map_search_type = '';

function updatePanelData(type) {
		if(type!=map_search_type){
			map.clearOverlays(); 
		}
		map_search_type = type;
		clicked = false;
		getMarkerPoints();
}

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
		    if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
	    this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}

var ajax = new sack();

function getSuburbList(sel, fieldid) {
    id = fieldid;
	var cityCode = sel.options[sel.selectedIndex].value;
	document.getElementById(id).options.length = 0;	
	if(cityCode.length>0){
		ajax.requestFile = 'actions/ajaxInterface.php?cityCode='+cityCode;
		ajax.onCompletion = createSuburbs;
		ajax.runAJAX();
	}
}

function createSuburbs(){
	var obj = document.getElementById(id);
	eval(ajax.response);
}

function getPointData(id, marker) {
    http_request = false;
	url = 'actions/ajaxInterface.php?id_point='+id;
    if (window.XMLHttpRequest) {
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
         http_request.overrideMimeType('text/xml');
    }
    } else if (window.ActiveXObject) { // IE
      try {
           http_request = new ActiveXObject("Msxml2.XMLHTTP");
          } catch (e) {
            try {
                 http_request = new ActiveXObject("Microsoft.XMLHTTP");
               } catch (e) {}
           }
    }

    if (!http_request) {
        alert('Poddaję się :( Nie mogę stworzyć instancji obiektu XMLHTTP');
        return false;
    }
    
     http_request.onreadystatechange = function() { setPointData(http_request, marker) };
     http_request.open('GET', url, true);
     http_request.send(null);
}

function setPointData(http_request, marker) {
	if (http_request.readyState == 4) {
    	if (http_request.status == 200) {
			marker.openInfoWindowHtml(http_request.responseText);	
			
  		} else {
            alert('Wystąpił problem z zapytaniem.');
        }
	}
}

function getMarkerPoints() {

	ulica_icon  = new GIcon(G_DEFAULT_ICON, "../img/maps/icon25.png");
	ulica_icon.shadow = 'img/maps/icon25s.png';
	ulica_icon.iconSize = new GSize(32,32);
    ulica_icon.shadowSize = new GSize(32,32);
	document.getElementById("loadingProgressBar").innerHTML = '<img src="/img/loading.gif" style="float: left;"><p style="line-height: 36px; padding: 0; margin: 0;">Proszę czekać...</p> Trwa wyszukiwanie ofert ';
	switch(type) {			
		case 'sell':
			document.getElementById("loadingProgressBar").innerHTML += '<span style="font-size: 10px;">(sprzedaż)</span>'; 
			var tab = new Array("price_min","price_max","area_min","area_max","rooms_count","estate_type","market","usertype");
			icon  = new GIcon(G_DEFAULT_ICON, "../img/maps/mm_20_red.png");
			percent = 37;			
			break;	
		case 'rent':
			document.getElementById("loadingProgressBar").innerHTML += '<span style="font-size: 10px;">(wynajem)</span>'; 
			var tab = new Array("price_min","price_max","rooms_count","estate_type","usertype","startdate");
			icon  = new GIcon(G_DEFAULT_ICON, "../img/maps/mm_20_blue.png");
			percent = 37;			
			break;	
		case 'room':
			document.getElementById("loadingProgressBar").innerHTML += '<span style="font-size: 10px;">(pokoje i stancje)</span>'; 
			var tab = new Array("price_min","price_max","rooms_people","usertype","startdate");
			icon  = new GIcon(G_DEFAULT_ICON, "../img/maps/mm_20_gray.png");
			percent = 42;			
			break;	
		case 'komercyjne':
			document.getElementById("loadingProgressBar").innerHTML += '<span style="font-size: 10px;">(komercyjne)</span>'; 
			var tab = new Array("price_min","price_max","komercyjne_type","area_min","area_max","usertype");
			icon  = new GIcon(G_DEFAULT_ICON, "../img/maps/mm_20_yellow.png");
			percent = 30;			
			break;	
		case 'land':
			document.getElementById("loadingProgressBar").innerHTML += '<span style="font-size: 10px;">(działki)</span>'; 
			var tab = new Array("price_min","price_max","land_type","usertype","area_min","area_max");
			icon  = new GIcon(G_DEFAULT_ICON, "../img/maps/mm_20_green.png");
			percent = 40;			
			break;			
	}
	 
	startLoader(type);
	document.getElementById("loadingProgressBar").style.display = "block";
	icon.shadow = 'img/maps/mm_20_shadow.png';
    icon.iconSize = new GSize(12,20);
    icon.shadowSize = new GSize(22,20);
		
				
  http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
	    
	    
	    if (!http_request) {
	        alert('Poddaję się :( Nie mogę stworzyć instancji obiektu XMLHTTP');
	        return false;
	    }
	
		 	bounds = map.getBounds();
		 	zoom = map.getZoom();		
			SouthWest = bounds.getSouthWest();
			NorthEast = bounds.getNorthEast();
						
			if(type=='komercyjne') {
				komercyjne_type = document.getElementById('komercyjne_ktype').value;
				url = 'actions/ajaxInterface.php?swx='+SouthWest.x+'&swy='+SouthWest.y+'&nex='+NorthEast.x+'&ney='+NorthEast.y+'&type='+type+'&ktype='+komercyjne_type+'&zoom='+zoom;				
			} else {			
			    url = 'actions/ajaxInterface.php?swx='+SouthWest.x+'&swy='+SouthWest.y+'&nex='+NorthEast.x+'&ney='+NorthEast.y+'&type='+type+'&zoom='+zoom;
			}    
 
		    for(i=0; i<tab.length; i++) {
				handle = document.getElementById(type+"_"+tab[i]);
				if(handle.multiple==false) {
					url += '&'+tab[i]+'='+handle.value;
				} else {
					for(j=1; j<handle.options.length; j++) {
						if(handle.options[j].selected) url += '&'+tab[i]+'%5B%5D='+handle.options[j].value;
					}
				}
			}
					
 			http_request.open('GET', url, true);
    		http_request.send(null);
    
    		http_request.onreadystatechange = function() { 	    
			if(!clicked) setMarkerPoints(http_request); 				
	};

} 

function getHref() {
	return 'index.php?nav1=filtr&nav2='+type;
}

function setMarkerPoints(http_request) {
    if (http_request.readyState == 4) {
    	if (http_request.status == 200) {
			var xmldoc = http_request.responseXML;
			id = new Array();
			map_x = new Array();
			map_y = new Array(); 
			map_lokalizacja = new Array(); 
			id = xmldoc.getElementsByTagName("id");
			map_x = xmldoc.getElementsByTagName("map_x");
			map_y = xmldoc.getElementsByTagName("map_y");
			map_lokalizacja = xmldoc.getElementsByTagName("map_lokalizacja");
			cm = xmldoc.getElementsByTagName("countmax");
			cl = xmldoc.getElementsByTagName("countlimit");
			try {
				countmax = cm[0].childNodes[0].nodeValue;
				countlimit = cl[0].childNodes[0].nodeValue;
				if(countmax==1) {
					document.getElementById('count').value="Na mapie zaznaczono "+countlimit+" najnowszych ofert sposród "+countmax+" odnalezionej w bazie szybko.pl";
					document.getElementById('percent').value="Uwaga! Tylko "+percent+"% ogloszeń jest oznaczonych na mapie google. Wyszukaj wszystkie ogłoszenia. >>>";
				}
				else {
					document.getElementById('count').value="Na mapie zaznaczono "+countlimit+" najnowszych ofert sposród "+countmax+" odnalezionych w bazie szybko.pl.";
					document.getElementById('percent').value="Uwaga! Tylko "+percent+"% ogloszeń jest oznaczonych na mapie google. Wyszukaj wszystkie ogłoszenia. >>>";
				}				
			} catch(e) { document.getElementById('count').value='Nie znaleziono ogłoszeń w określonej lokalizacji' }
			
			//map.clearOverlays(); 
			if(addresspoint!=undefined) map.addOverlay(marker=createPin(addresspoint));   			
			for(var i=0;i<id.length;i++) {	
				point = new GLatLng(map_y[i].childNodes[0].nodeValue, map_x[i].childNodes[0].nodeValue);
				switch(map_lokalizacja[i].childNodes[0].nodeValue){
				case 'dokladne':
					var marker=createMarker(point,id[i].childNodes[0].nodeValue,icon);
					map.addOverlay(marker);
					break; 
				case 'ulica':
					map.addOverlay(marker=createMarker(point, id[i].childNodes[0].nodeValue,ulica_icon));
					break; 
				}
			}
			stopLoader();
		} else {
			stopLoader();
			alert('Wystąpił problem z zapytaniem.');
		}		
	}

}


