// jquery.rcz.map.js v0.1, last update: 18.3.2011
// Map search for Reality.CZ Web2011
// Copyright (c) 2011 Lubos Bielak  <bielak@reality.cz>
// RCZ namespace adjustments Jiri Jezdinsky, <jezdinsky@reality.cz>
// Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
//
// Dependencies: jquery-1.4.2, jquery-ui-1.8.2, jquery.rcz

RCZ0 = RCZ0.extend({
	map: {
		picdir: '/images/design/',
		ZamerovacIcoLast: 0,
		Zamerovac: undefined,
		ZamerovacDohledanoText: undefined,
		ZamerovacMap: undefined,
		ZamerovacPolohaSave: undefined,
		ZamerovacSavePoloha: undefined,
		ZamerovacSave: undefined,
		ZamerovacPlus: undefined,
		ZamerovacMinus: undefined
	},
	mapInit: function() {
		var self = this;
		// sestaveni mapy
		var zoom = self.options.gpszoom || 11;
		if (zoom < 7) zoom = 7;
		if (zoom > 16) zoom = 16;
				
		//self.map.ZamerovacPoloha = new google.maps.LatLng( self.options.gpsx || 50.079, self.options.gpsy || 14.43 );
		if(typeof(self.options.gpsx) != 'undefined' && typeof(self.options.gpsy) != 'undefined'){
			self.map.ZamerovacPoloha = new google.maps.LatLng(self.options.gpsx, self.options.gpsy);
		}else{
			self.map.ZamerovacPoloha = self.GetGEO();
		}
		self.map.ZamerovacMap = new google.maps.Map($('#mapHled')[0], {
				center: self.map.ZamerovacPoloha,
				zoom: zoom,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				//mapTypeControl: false,
				panControl: false,
				streetViewControl: false,
				zoomControl: false,
				scaleControl: true,
				scaleControlOptions: {position: google.maps.ControlPosition.BOTTOM_LEFT},
				zoomControlOptions: {
					style: google.maps.ZoomControlStyle.SMALL
				}
		});

		// sestaveni zamerovace
		var shape = { coord: [134, 134, 102], type: 'circle'};
		self.map.Zamerovac = new google.maps.Marker({
			position: self.map.ZamerovacPoloha, 
			map: self.map.ZamerovacMap,
			draggable: true,
			raiseOnDrag: false,
			zIndex: 9000,
			shape: shape
		});
		self.mapZamerovacIkonaA('zamerovac_all.png',self.map.ZamerovacIcoLast);

		// sestaveni poloh na zamerovaci
		self.mapZamerovacTlacitka();

		if (!$('#mapaPopis').html()) self.mapInfoText('Vyberte oblast ohraničenou zaměřovačem pro vyhledání nemovitostí.', '');

		// ================ udalosti Mapy ================ 
		google.maps.event.addListener(self.map.ZamerovacMap, "zoom_changed", function(event) {
			if (this.getZoom() < 7) {
				this.setZoom(this.getZoom()+1);
//				self.mapInfoText('Toto je hraniční hodnota pro oddálení.');
			}
			if (this.getZoom() > 16) {
				this.setZoom(this.getZoom()-1);
//				self.mapInfoText('Toto je hraniční hodnota pro přiblížení.');
			}
			self.map.ZamerovacPoloha=this.getCenter();
			self.map.Zamerovac.set('position',self.map.ZamerovacPoloha);
			self.mapGetPosition();
			self.mapZamerovacTlacitka();
		});
		google.maps.event.addListener(self.map.ZamerovacMap, "dblclick", function(event) { // pro pripad priblizeni kliknutim mimo presunu lupu na toto misto
			self.map.ZamerovacPoloha=event.latLng;
			self.map.Zamerovac.set('position',self.map.ZamerovacPoloha);
		});
		google.maps.event.addListener(self.map.ZamerovacMap, "click", function(event) {
			self.map.Zamerovac.set('position',event.latLng);
			self.mapZamerovacPozice(event);
		});
	/*	google.maps.event.addListener(self.map.ZamerovacMap, "tilesloaded", function(event) {  //po vykresleni vseho spusti toto  /addListenerOnce/
		});*/

		google.maps.event.addListener(self.map.ZamerovacMap, "dragend", function(event) {
			var bounds = this.getBounds();
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();
			var lngSpan = (northEast.lng() - southWest.lng())/2;
			var latSpan = (northEast.lat() - southWest.lat())/2;
			var ZamerovacPolohaLat = self.map.ZamerovacPoloha.lat();
			var ZamerovacPolohaLng = self.map.ZamerovacPoloha.lng();
			if (self.map.ZamerovacPoloha.lng()>northEast.lng()){ //kontrola napravo
				ZamerovacPolohaLng = northEast.lng()-lngSpan/10;
			}
			if (self.map.ZamerovacPoloha.lng()<southWest.lng()){ //kontrola nalevo
				ZamerovacPolohaLng = southWest.lng()+lngSpan/10;
			}
			if (self.map.ZamerovacPoloha.lat()>northEast.lat()){ //kontrola nahore
				ZamerovacPolohaLat = northEast.lat()-latSpan/10;
			}
			if (self.map.ZamerovacPoloha.lat()<southWest.lat()){ //kontrola dole
				ZamerovacPolohaLat = southWest.lat()+latSpan/10;
			}
			self.map.ZamerovacPoloha=new google.maps.LatLng(ZamerovacPolohaLat,ZamerovacPolohaLng)
			self.map.Zamerovac.set('position',self.map.ZamerovacPoloha);
			self.mapGetPosition();
			self.mapZamerovacTlacitka();
		});

		// ================ udalosti Zamerovace ================ 
		google.maps.event.addListener(self.map.Zamerovac, "dragstart", function(event) {
			if(!$.browser.msie) self.mapZamerovacIkonaA('zamerovac_all.png',548);
		});
		google.maps.event.addListener(self.map.Zamerovac, "dragend", function(event) {
			self.mapZamerovacPozice(event);
			self.mapZamerovacTlacitka();
			self.map.ZamerovacIcoLast = '274';
			self.mapZamerovacIkonaA('zamerovac_all.png',self.map.ZamerovacIcoLast);
		});
		google.maps.event.addListener(self.map.Zamerovac, "dblclick", function(event) {
			self.map.ZamerovacMap.panTo(self.map.ZamerovacPoloha);
			self.mapZoomInOut('+1');
		});
		google.maps.event.addListener(self.map.Zamerovac, "drag", function(event) {
//			self.mapInfoText('GPS: '+event.latLng);
		});
		google.maps.event.addListener(self.map.Zamerovac, "mouseover", function(event) {
			if(!$.browser.msie)self.mapZamerovacIkonaA('zamerovac_all.png',548);
		});
		google.maps.event.addListener(self.map.Zamerovac, "mouseout", function(event) {
			self.mapZamerovacIkonaA('zamerovac_all.png',self.map.ZamerovacIcoLast);
		});
		self.mapGetPosition();
		if (RCZ_IE) {
//			$('#mapCntnr').append('<div class="IEstin"></div>');
		}
		//naseptavani adresy pres googlovske funkce
		var geocoder = new google.maps.Geocoder();
		$("#address").autocomplete({
			source: function(request, response) {
				var Omezeni = new google.maps.LatLngBounds(new google.maps.LatLng(48.48, 11.96), new google.maps.LatLng(51.17, 18.92));
				geocoder.geocode( {'address': request.term, 'region': 'cs', 'bounds': Omezeni}, function(results, status) {
					response($.map(results, function(item) {
						//pokud neni CZ, pak zahazuji
						for (var i = 0; i < item.address_components.length; i++){
							var addr = item.address_components[i];
							if (addr.types[0] == 'country' && addr.short_name != 'CZ') return;
						}
						return {
							label: item.formatted_address,
							value: item.formatted_address,
							latitude: item.geometry.location.lat(),
							longitude: item.geometry.location.lng(),
							vw: item.geometry.viewport
						}
					}));
				});
			},
			select: function(event, ui) {
				self.map.ZamerovacMap.fitBounds(ui.item.vw);
				var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
				self.map.ZamerovacPoloha=location;
				self.map.ZamerovacMap.panTo(location);
				self.mapZamerovacTlacitka();
				self.map.ZamerovacIcoLast = '274';
				if(!$.browser.msie)self.mapZamerovacIkonaA('zamerovac_all.png',self.map.ZamerovacIcoLast);
				self.map.Zamerovac.set('position',self.map.ZamerovacPoloha);
				self.mapGetPosition();
			}
		});
		//konec dohledavani
	},
	mapZamerovacPozice: function(event){
		var self = this;
		self.map.ZamerovacPoloha=event.latLng;
		self.mapGetPosition();
		self.map.ZamerovacPolohaSave = self.map.ZamerovacPoloha;
		if(!$.browser.msie)self.mapZamerovacIkonaA('zamerovac_all.png',self.map.ZamerovacIcoLast);
		self.mapZamerovacTlacitka();
	},
	mapZoomInOut: function(Krok){
		var self = this;
		self.map.ZamerovacMap.setZoom(self.map.ZamerovacMap.getZoom()+parseInt(Krok));
	},
	mapZamerovacIkona: function(IkonaP){
		var self = this;
		var ZamerovacIco = new google.maps.MarkerImage(self.map.picdir+IkonaP,
			new google.maps.Size(268,268),
			new google.maps.Point(0,0),
			new google.maps.Point(134,134)
		);
		self.map.Zamerovac.setIcon(ZamerovacIco);      
	},
	mapZamerovacIkonaA: function(IkonaP,IcoMove){
		var self = this;
		var ZamerovacIco = new google.maps.MarkerImage(self.map.picdir+IkonaP,
			new google.maps.Size(268,268),
			new google.maps.Point(0,IcoMove),
			new google.maps.Point(134,134)
		);
		self.map.Zamerovac.setIcon(ZamerovacIco);      
	},
	mapGetPosition: function(){
		var self = this;
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode({'latLng': self.map.ZamerovacPoloha}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				if (results) {
					var Ulice, Sousedstvi, ObecC, Obec, Okres, Kraj, Zeme, Zem;
					var z = self.map.ZamerovacMap.getZoom();
					for (var i = 0; i < results[0].address_components.length; i++){
						// alert(results[0].address_components[i].types[0]+': '+results[0].address_components[i].long_name);
						switch (results[0].address_components[i].types[0]) {
							case 'route':
								Ulice = results[0].address_components[i].long_name; break;
							case 'neighborhood':
								Sousedstvi = results[0].address_components[i].long_name; break;
							case 'sublocality':
								ObecC = results[0].address_components[i].long_name; break;
							case 'locality':
								Obec = results[0].address_components[i].long_name; break;
							case 'administrative_area_level_2':
								Okres = results[0].address_components[i].long_name; break;
							case 'administrative_area_level_1':
								Kraj = results[0].address_components[i].long_name; break;
							case 'country': 
								Zeme = results[0].address_components[i].long_name;
								Zem = results[0].address_components[i].short_name;
					} }
					self.map.ZamerovacDohledanoText = '';
					if (Zem != 'CZ'){
						//self.map.ZamerovacDohledanoText = Zeme;
						//pokud jsem mimo CR vracim na zacatek
						self.map.ZamerovacPoloha = self.GetGEO();
						self.map.Zamerovac.set('position',self.map.ZamerovacPoloha);
						self.map.ZamerovacMap.panTo(self.map.ZamerovacPoloha);
						self.mapZamerovacTlacitka();
						//self.map.ZamerovacMap.setZoom(11);
						self.mapGetPosition();
					}else {
						if (ObecC == Obec) ObecC = '';
						if (Ulice) Ulice = Ulice.replace(/^\d+$/, '');
						if (Obec == 'Praha') {
							if (Sousedstvi) {
								Okres = ', '+(ObecC||Obec);
								Obec = Sousedstvi;
							} else {
								Okres = (ObecC) ? ', '+Obec : Obec;
								Obec = ObecC;
							}
							ObecC = '';
						} else {
							if (Kraj) Kraj = (Kraj == 'Vysočina') ? 'kraj '+Kraj : Kraj+' kraj';
							if (z >= 11) {
								if (Obec == Okres) Okres = ', '+Kraj;
							} else {
								if (z < 9) Okres = ''
							}
							if (Okres && Okres != ', '+Kraj) Okres = ', okres '+Okres;
						}
						if (Ulice && z >= 15) self.map.ZamerovacDohledanoText += Ulice+', ';
						if (ObecC && z >= 13) self.map.ZamerovacDohledanoText += ' ('+ObecC+')';
						if (Obec) {
							self.map.ZamerovacDohledanoText += Obec;
							if (z <= 12) {
								var okolo = 5*Math.pow(2, 11-self.map.ZamerovacMap.getZoom());
								self.map.ZamerovacDohledanoText += ', okolí ' + okolo.toString().replace(/\./, ',') + ' km';
							}
						}
						//if (Okres && z >= 9) self.map.ZamerovacDohledanoText += Okres;
						//if (Kraj && z < 11) self.map.ZamerovacDohledanoText += ', '+Kraj;
						self.map.ZamerovacDohledanoText = self.map.ZamerovacDohledanoText.replace(/^, /, '');
					}
					self.mapInfoText('Hledám v mapě: ', self.map.ZamerovacDohledanoText);
					self.mapZamerovacVyplnForm();
					//self.mapInfoText('Dohledáno: '+self.map.ZamerovacDohledanoText);
				}else{
					//alert("Bez informaci pro danou polohu.");
				}
			}else{
				//alert("Poloha nenalezena, chyba: " + status);
			}
		});
	},
	mapInfoText: function(text, oblast){
		text = '<div class="fll pl3">'+text+'</div>';
		if (oblast)	text += ' <div class="ui-corner-all"><a href="#map" class="linkselectLink">'+oblast+'</a></div>';
		$('#mapaPopis').html('<div style="width:1000px">'+text+'</div>');
		if (RCZ_IE) $("#mapaPopis div.ui-corner-all").cornerz({radius: 4, fixIE:false});

	},
	mapZamerovacVyplnForm: function(){
		var self = this;
		//if(typeof(Vyber) != "undefined"){Vyber.setMap(null);}
		//self.map.ZamerovacMap.panTo(self.map.ZamerovacPoloha);
		var bounds = self.map.ZamerovacMap.getBounds();
		if (!bounds) return;
		var southWest = bounds.getSouthWest();//vlevo dole
		var northEast = bounds.getNorthEast();//pravy horni
		var lngSpan = (northEast.lng() - southWest.lng())/6.2;
		var latSpan = (northEast.lat() - southWest.lat())/6.2;
		/*
		var CoVybrano = [
			new google.maps.LatLng(self.map.ZamerovacPoloha.lat()+latSpan, self.map.ZamerovacPoloha.lng()+lngSpan),
			new google.maps.LatLng(self.map.ZamerovacPoloha.lat()+latSpan, self.map.ZamerovacPoloha.lng()-lngSpan),
			new google.maps.LatLng(self.map.ZamerovacPoloha.lat()-latSpan, self.map.ZamerovacPoloha.lng()-lngSpan),
			new google.maps.LatLng(self.map.ZamerovacPoloha.lat()-latSpan, self.map.ZamerovacPoloha.lng()+lngSpan),
			new google.maps.LatLng(self.map.ZamerovacPoloha.lat()+latSpan, self.map.ZamerovacPoloha.lng()+lngSpan)
		];
		Vyber = new google.maps.Polygon({
			paths: CoVybrano,
			strokeColor: "#FF0000",
			strokeOpacity: 0.5,
			strokeWeight: 1,
			fillColor: "#FF0000",
			fillOpacity: 0.15
		});
		Vyber.setMap(self.map.ZamerovacMap);
		*/
		var LD = new google.maps.LatLng(self.map.ZamerovacPoloha.lat()-latSpan, self.map.ZamerovacPoloha.lng()-lngSpan);
		var PH = new google.maps.LatLng(self.map.ZamerovacPoloha.lat()+latSpan, self.map.ZamerovacPoloha.lng()+lngSpan);

		$("#realf").find('input[name^="map"]').each(function() {
			switch (this.name) {
				case 'mapzs1': this.value=Math.round(LD.lat()*1e5)/1e5; break;
				case 'mapzs2': this.value=Math.round(PH.lat()*1e5)/1e5; break;
				case 'mapzd1': this.value=Math.round(LD.lng()*1e5)/1e5; break;
				case 'mapzd2': this.value=Math.round(PH.lng()*1e5)/1e5; break;
				case 'maphled': this.value=1; break;
				case 'maptxt': this.value=$("#mapaPopis a").html(); break;
				case 'mapzoom': this.value=self.map.ZamerovacMap.getZoom(); break;
			}
		});
	},
	mapZamerovacTlacitka: function(){
		var self = this;
		var diff = (200.88/(3*Math.pow(2,self.map.ZamerovacMap.getZoom()))); //koeficient pro polomer i pri zoomu

		//Ikona pro rozbaleni tlacitka
		var ZamerovacSaveIcoSave = new google.maps.MarkerImage( self.map.picdir+'zam_tlac_save.png',
			new google.maps.Size(127,39),
			new google.maps.Point(0,0),
			new google.maps.Point(24,38)
		);
		//Ikona pro zruseni tlacitka
		var ZamerovacSaveIcoNoSave = new google.maps.MarkerImage(self.map.picdir+'zamerovac_save.png');
		//Ikona pro zoom
		var ZamerovacSaveZoomIco = new google.maps.MarkerImage(self.map.picdir+'zamerovac_zoom.png');

		//Ikona pro ulozeni polohy
		self.map.ZamerovacSavePoloha = new google.maps.LatLng(self.map.ZamerovacPoloha.lat()-diff*1.21,self.map.ZamerovacPoloha.lng()+diff*1.6);
		if(typeof(self.map.ZamerovacSave) == "undefined"){
			self.map.ZamerovacSave = new google.maps.Marker({
				position: self.map.ZamerovacSavePoloha,
				map: self.map.ZamerovacMap,
				title: "Vyhledat",
				draggable: false,
				clickable: true,
				zIndex: 9993,
				icon: ZamerovacSaveIcoNoSave
			});
			//Nastaveni odchytnuti ulozeni
			google.maps.event.addListener(self.map.ZamerovacSave, "click", function(event) {
				self.mapZamerovacVyplnForm();
				$("form#hlfrm09").submit();
				$('#mapCntnr').hide();
				//self.mapInfoText('Hledám v mapě: ', self.map.ZamerovacDohledanoText);
			});

			//Zmena ikony
			google.maps.event.addListener(self.map.ZamerovacSave, "mouseover", function(event) {
				self.map.ZamerovacSave.setIcon(ZamerovacSaveIcoSave);
			});
			google.maps.event.addListener(self.map.ZamerovacSave, "mouseout", function(event) {
				self.mapZamerovacIkonaA('zamerovac_all.png',self.map.ZamerovacIcoLast);
				self.map.ZamerovacSave.setIcon(ZamerovacSaveIcoNoSave);
			});
			google.maps.event.addListener(self.map.ZamerovacSave, "dragstart", function(event) {
//    			self.map.ZamerovacSave.setDraggable(false);
			});
		}else{
			self.map.ZamerovacSave.set('position',self.map.ZamerovacSavePoloha);
			self.map.ZamerovacSave.setIcon(ZamerovacSaveIcoNoSave);
		}                                                                                             		

		//Ikona pro zoom +
		self.map.ZamerovacPlusPoloha = new google.maps.LatLng(self.map.ZamerovacPoloha.lat()+diff*0.95,self.map.ZamerovacPoloha.lng()+diff*1.44);
		if(typeof(self.map.ZamerovacPlus) == "undefined"){
			self.map.ZamerovacPlus = new google.maps.Marker({
				position: self.map.ZamerovacPlusPoloha,
				map: self.map.ZamerovacMap,
				title: "Přiblížit",
				draggable: true,
				clickable: true,
				zIndex: 9991,
				icon: ZamerovacSaveZoomIco
			});
			//udalosti
			google.maps.event.addListener(self.map.ZamerovacPlus, "click", function(event) {
				self.map.ZamerovacMap.panTo(self.map.ZamerovacPoloha);
				self.mapZoomInOut('+1');
			});
			google.maps.event.addListener(self.map.ZamerovacPlus, "dragstart", function(event) {
				self.map.ZamerovacPlus.setDraggable(false);
			});
		}else{
			self.map.ZamerovacPlus.set('position',self.map.ZamerovacPlusPoloha);
		}

		//Ikona pro zoom -
		self.map.ZamerovacMinusPoloha = new google.maps.LatLng(self.map.ZamerovacPoloha.lat()+diff*0.74,self.map.ZamerovacPoloha.lng()+diff*1.8);
		if(typeof(self.map.ZamerovacMinus) == "undefined"){
			self.map.ZamerovacMinus = new google.maps.Marker({
				position: self.map.ZamerovacMinusPoloha,
				map: self.map.ZamerovacMap,
				title: "Oddálit",
				draggable: true,
				clickable: true,
				zIndex: 9992,
				icon: ZamerovacSaveZoomIco
			});
			//udalosti
			google.maps.event.addListener(self.map.ZamerovacMinus, "click", function(event) {
				self.map.ZamerovacMap.panTo(self.map.ZamerovacPoloha);
				self.mapZoomInOut('-1');
			});
			google.maps.event.addListener(self.map.ZamerovacMinus, "dragstart", function(event) {
				self.map.ZamerovacMinus.setDraggable(false);
			});
		}else{
			self.map.ZamerovacMinus.set('position',self.map.ZamerovacMinusPoloha);
		}
	},
	GetGEO: function(){
		var self = this;
		var GEOLat, GEOLng;
		//PRESKAKUJEME
		if(0 && navigator.geolocation){
				// GEO z W3C 
			navigator.geolocation.getCurrentPosition(function(position){
				GEOLat = position.coords.latitude;
				GEOLng = position.coords.longitude;
				// presnost v m je v position.coords.accuracy
			}, function() {
				// pripadna vetev pro to, ze se nic nenaslo
			}, {timeout:0});
		}
		//PRESKAKUJEME 
		if(0 && google.gears && (typeof(GEOLat) == 'undefined' || typeof(GEOLng) == 'undefined')){
			// GEO z Google Gears
			var geo = google.gears.factory.create('beta.geolocation');
			geo.getCurrentPosition(function(position){
				GEOLat = position.latitude;
				GEOLng = position.longitude;
			}, function() {
				// pripadna vetev pro to, ze se nic nenaslo
			});
		}
		if (google.loader.ClientLocation && (typeof(GEOLat) == 'undefined' || typeof(GEOLng) == 'undefined')){
			// GEO z IP adresy
			var currentLocation;
			currentLocation = google.loader.ClientLocation;
			GEOLat = currentLocation.latitude;
			GEOLng = currentLocation.longitude;
		}
		
		// Kontrola na cizince
		if(typeof(GEOLat) != 'undefined' && typeof(GEOLng) != 'undefined'){
			geocoder = new google.maps.Geocoder();
			var Cizinec = '?';
			geocoder.geocode({'latLng': self.map.ZamerovacPoloha}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					if (results) {
						for (var i = 0; i < results[0].address_components.length; i++){
							if (results[0].address_components[i].types[0] == 'country'){
								Cizinec = results[0].address_components[i].short_name;
							} 
						}
						if (Cizinec != 'CZ'){
							GEOLat == 'undefined';
							GEOLng == 'undefined';
						}
					}
				}
			});
		}
		
		// kontrola zda se neco naslo, nebo zda to neni cizinec
		if(typeof(GEOLat) == 'undefined' || typeof(GEOLng) == 'undefined'){
			GEOLat = 50.079;
			GEOLng = 14.43;    
		}

		return(new google.maps.LatLng(GEOLat, GEOLng));
	}
});

