// fullbiz.gmaps.js
// Descrição: Arquivo que concentra todas as funcionalidades baseadas no google maps V3 (não compatível com IE)
// Dependências: Google Maps API V3
// Versão inicial:	2011.03.18.L
// Versão atual:	2011.03.18.L

//declara variavais globais
var gLocalSearch;
var gMap;
var gInfoWindow;
var gSelectedResults = [];
var gCurrentResults = [];
var gSearchForm;

var gIcon = new google.maps.MarkerImage(
	"http://google-maps-icons.googlecode.com/files/info.png",
	new google.maps.Size(32, 37),
	new google.maps.Point(0,0),
	new google.maps.Point(0, 7)
);


function start_maps() {
	//carrega mapas
	if ($("div.load-gmap").length>0) {
		$("div.load-gmap").each(function(){
			var cor = $(this).find("input.gmaps-cor").val();
			var km = $(this).find("input.gmaps-km").val();
			var icon = $(this).find("input.gmaps-icon").val();
			var zoom = $(this).find("input.gmaps-zoom").val();
			var mapid = $(this).attr("id");
			var v = new Array();
			i = -1;
			$(this).find("ul li").each(function(){
				i++;
				var str = $(this).html()+'||'+cor+'||'+km+'||'+icon;
				v[i] = str.split("||");
			});
			$(this).html("Carregando mapa...");
			mapa_imovel(v,mapid,zoom);
		});
	}
}

//carrega o mapa do imóvel
function mapa_imovel(v,mapid,zoommap) {
	if ($("#"+mapid).length>0) {
		var position = new google.maps.LatLng(parseFloat(v[0][0]),parseFloat(v[0][1]));
		var gOpts = {
		  zoom: parseInt(zoommap),
		  scrollwheel: false,
		  streetViewControl: true,
		  center: position,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		gMap = new google.maps.Map(document.getElementById(mapid), gOpts);
		for (var i=0;i<v.length;i++) {
			if ($("body").hasClass("browserIE")) {
				//se for IE, atrasa 2 segundos a impressão do círculo pq... é o IE!
				var x = v[i];
				setTimeout(function(){ mapa_imovel_marker(x); },2000);
			} else {
				mapa_imovel_marker(v[i]);
			}
		}
		if ($("#gmap-nearby").length>0) {
			$("<link/>", { rel: "stylesheet", type: "text/css", href: "http://www.google.com/uds/css/gsearch.css" }).appendTo("head");
			$("#gmap-nearby ul li a").click(function(){
				$("#gmap-nearby ul li a.active").removeClass("active");
				var procurar = $(this).attr("rel");
				mapa_imovel_search(procurar);
				$(this).addClass("active");
				return false;
			})
		}
	}
}

//adiciona um ponto/marcador no mapa
function mapa_imovel_marker(v) {
	var marker_position = new google.maps.LatLng(parseFloat(v[0]),parseFloat(v[1]));
	if (v[2]=='circulo') {
		/*
		var gCircle = new google.maps.Circle({
		  map: gMap,
		  strokeColor: v[4],
		  strokeWeight: 2,
		  strokeOpacity: 1,
		  zIndex: 5000,
		  radius: eval(v[5]),
		  center: marker_position
		});
		*/
	} else {
		if (v[6]) var icone = 'img/design/gmaps_icon.png'; else icone = '';
		var marker = new google.maps.Marker({
			position: marker_position, 
			map: gMap,
			icon: icone
		});
		if (v[3]!="") {
			var infowindow = new google.maps.InfoWindow({
				content: v[3]
			});
			google.maps.event.addListener(marker, 'click', function() {
				infowindow.open(gMap,marker);
			});
		}
	}
}

function mapa_imovel_search(procurar) {
	// Create one InfoWindow to open when a marker is clicked.
	gInfoWindow = new google.maps.InfoWindow;
	google.maps.event.addListener(gInfoWindow, 'closeclick', function() {
		unselectMarkers();
	});

	gLocalSearch = new GlocalSearch();
	gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
	
	var vp = procurar.split("|");
	gIcon = new google.maps.MarkerImage("http://google-maps-icons.googlecode.com/files/"+vp[1]+".png");
	doSearch(vp[0]);
	
}

function unselectMarkers() {
	for (var i = 0; i < gCurrentResults.length; i++) {
		gCurrentResults[i].unselect();
	}
}

function doSearch(query) {
	gLocalSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);
	gLocalSearch.setCenterPoint(gMap.getCenter());
	gLocalSearch.execute(query);
}
	
// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch() {
	if (!gLocalSearch.results) return;
	for (var i = 0; i < gCurrentResults.length; i++) {
		gCurrentResults[i].marker().setMap(null);
	}
	// Close the infowindow
	//gInfoWindow.close();
	gCurrentResults = [];
	for (var i = 0; i < gLocalSearch.results.length; i++) {
		gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));
	}
	//var attribution = gLocalSearch.getAttribution();
	//if (attribution) {
	//	document.getElementById("searchwell").appendChild(attribution);
	//}
	
	// Move the map to the first result
	//var first = gLocalSearch.results[0];
	//gMap.setCenter(new google.maps.LatLng(parseFloat(first.lat), parseFloat(first.lng)));
}

function LocalResult(result) {
	var me = this;
	me.result_ = result;
	me.resultNode_ = me.node();
	me.marker_ = me.marker();
	google.maps.event.addDomListener(me.resultNode_, 'click', function() {
		me.select();
	});
	//document.getElementById("searchwell").appendChild(me.resultNode_);
}

LocalResult.prototype.node = function() {
	if (this.resultNode_) return this.resultNode_;
	return this.html();
};

// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function() {
	var me = this;
	if (me.marker_) return me.marker_;
	var marker = me.marker_ = new google.maps.Marker({ position: new google.maps.LatLng(parseFloat(me.result_.lat), parseFloat(me.result_.lng)), icon: gIcon, map: gMap });
	google.maps.event.addListener(marker, "click", function() {
		me.select();
	});
	return marker;
};

// Unselect any selected markers and then highlight this result and
// display the info window on it.
LocalResult.prototype.select = function() {
	unselectMarkers();
	this.selected_ = true;
	gInfoWindow.setContent(this.html(true));
	gInfoWindow.open(gMap, this.marker());
};

LocalResult.prototype.isSelected = function() {
	return this.selected_;
};

// Remove any highlighting on this result.
LocalResult.prototype.unselect = function() {
	this.selected_ = false;
};

// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.html = function() {
	var me = this;
	var container = document.createElement("div");
	container.className = "unselected";
	container.appendChild(me.result_.html.cloneNode(true));
	return container;
}

  
$(document).ready(function(){
	start_maps();
});
//GSearch.setOnLoadCallback(start_maps);


