/* API GOOGLE MAPS - BY OZUNA@OZUNA.COM.BR */

var enderecoEmp = null;
var mapaObj = null;
var infoWindow = null;
var gInfoWindow = null;
var directionService = null;
var directionsRenderer = null;
var currentDirections = null;
var gLocalSearch = null;
var intervaloInteresse = null;
var bounds = null;
var gCurrentResults = [];
var gLocalSearch;
var mapaObj;
var gInfoWindow;
var gSelectedResults = [];
var iconBusca = null;




function initialize(endereco)
{
	enderecoEmp = endereco;
	
	var uf = endereco.split("/");
	
	var myLatlng = new google.maps.LatLng(-23.548943, -46.638818);
	var myOptions = {
		zoom: (uf[1] == "RJ" ? 17 : 15),
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	mapaObj = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	google.maps.event.addListener(mapaObj, 'tilesloaded', function() {
		$(".holdemap input").show();
	});
	
	directionService = new google.maps.DirectionsService();
    directionsRenderer = new google.maps.DirectionsRenderer({ map: mapaObj });
    directionsRenderer.setPanel(document.getElementById("info-rota"));
	google.maps.event.addListener(directionsRenderer, 'directions_changed', function() {
        if(currentDirections){
            oldDirections.push(currentDirections);
        }
        currentDirections = directionsRenderer.getDirections();
    });
	
	geocoder = new google.maps.Geocoder();
	
	gInfoWindow = new google.maps.InfoWindow;
	google.maps.event.addListener(gInfoWindow, 'closeclick', function() {
		unselectMarkers();
	});
	
	gLocalSearch = new GlocalSearch();
	gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
	
	markerEmpreendimento();
}



function markerEmpreendimento()
{
    geocoder.geocode({ 'address' : enderecoEmp }, function(result, status){
        if (status == google.maps.GeocoderStatus.OK) {
			mapaObj.setCenter(result[0].geometry.location);
            var marker = new google.maps.Marker({
				position	: result[0].geometry.location,
				map			: mapaObj,
				icon		: "_images/empreendimento.gif" 
			});
			
			bounds = new google.maps.LatLngBounds();
			
			infoWindow = new google.maps.InfoWindow();
			google.maps.event.addListener(marker, 'click', function() {
				infoWindow.open(mapaObj, marker);
			});
			infoWindow.setContent('<div id="teste55" style="width:132px; height:45px; margin:12px 0 0 37px;"><a href="javascript:;" onclick="openInteracao(\'agendevisita\',\'\',\'\',\'\',\'\',\'\',\'\');"><img src="_images/agende_mapa.png" alt="" /></a></div>');
			infoWindow.open(mapaObj, marker);
			
        } else {
			
			$("#localizacaoaba").hide();
			$("#boxmapa").hide();
			$(".abas-outros-imovel > li:eq(1) > a").trigger("click")
        }
    });
}


var resultMAPA = null;
var statusMAPA = null;

function tracarRota(emp, idemp, local, estado, cidade)
{
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
	if(jQuery("#email-map").val() == false || emailPattern.test(jQuery("#email-map").val()) == false)
	{
		alert("Preencha seu email corretamente.");
		return false;
	}
	if(jQuery("#endereco-map").val() == false)
	{
		alert("Preencha seu endereço.");
		return false;
	}
	
	
	var ulrInt = "";
	ulrInt += 'http://interacoes2.tempsite.ws/impressaoderota-actions.php';
	ulrInt += '?produto='+emp+'&idEmpreendimento='+idemp+'&localidade='+local+'&estado='+estado+'&cidade='+cidade+'&email='+jQuery("#email-map").val();
	jQuery("#iframe-int").attr("src", ulrInt);
	jQuery("#iframe-int").attr("src", ulrInt);
	
	
	var novoVal = 'imovel-print.php?idEmpreendimento='+idemp+'&rota='+$("#tipo-map").val()+' '+$("#endereco-map").val()+' '+$("#estado-map").val();
	
	//var novoVal = $("#link-print-rota").attr("href")+"&rota="+$("#tipo-map").val()+" "+$("#endereco-map").val()+" "+$("#estado-map").val();
	//var novoVal = url+"&rota="+$("#tipo-map").val()+" "+$("#endereco-map").val()+" "+$("#estado-map").val();
	
	$("#link-print-rota").attr("href", novoVal);
	$("#link-print-rota").html("Imprimir rota");
	$("#link-print-rota").show();
	
    var tipo 		= $("#tipo-map").val();
    var desc 		= $("#endereco-map").val();
    var uf 			= $("#estado-map").val();
    var textoBusca 	= tipo +" "+ desc +" "+ uf;
	
    requestMapaRota = {
        origin: textoBusca,
        destination: enderecoEmp,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    }
	   
	$(".holdemap > input").css('right',357);
	
	directionService.route(requestMapaRota, function(result, status){
		resultMAPA = result;
		statusMAPA = status;
        setTimeout("tracarRotaFinal(resultMAPA, statusMAPA)",1000);
    });
}

function tracarRotaFinal(result,status){
	if(status == google.maps.DirectionsStatus.OK){
		directionsRenderer.setDirections(result);
		infoWindow.close();
		$("#map_canvas").css("width", "653px");
		$("#info-rota").css("display", "block");
		//pageTracker._trackPageview("impressaoderota-visualizacao");
	}else{
		alert("Não foi possivel localizar o seu endereço.");
	}
}


function scrollToMap(element)
{
	$(".abas-imagens-imovel li:eq(0)").show();
	$("#boxmapa").show();
	$('html, body').animate({scrollTop: $(element).offset().top},300);
}




//PONTOS DE INTERESSE
function unselectMarkers()
{
	for(var i = 0; i < gCurrentResults.length; i++)
	{
		gCurrentResults[i].unselect();
	}
}

function LocalResult(result)
{
	var me = this;
	me.result_ = result;
	me.resultNode_ = me.node();
	me.marker_ = me.marker();
	
	google.maps.event.addDomListener(me.resultNode_, 'mouseover', function() {
		// Highlight the marker and result icon when the result is
		// mouseovered.  Do not remove any other highlighting at this time.
		me.highlight(true);
		});
	
		google.maps.event.addDomListener(me.resultNode_, 'mouseout', function() {
		// Remove highlighting unless this marker is selected (the info
		// window is open).
		if (!me.selected_) me.highlight(false);
	});
		
	google.maps.event.addDomListener(me.resultNode_, 'click', function() {
		me.select();
	});
	
}

LocalResult.prototype.node = function()
{
	if (this.resultNode_) return this.resultNode_;
	return this.html();
};

// Returns the mapaObj 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: iconBusca, map: mapaObj});
		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(mapaObj, 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;
}


GSearch.setOnLoadCallback(OnLoad);



function OnLocalSearch()
{
	if (!gLocalSearch.results) return;
	
	// Clear the map and the old search well
	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();
	
	
	// Move the map to the first result
	//var first = gLocalSearch.results[0];
	//mapaObj.setCenter(new google.maps.LatLng(parseFloat(first.lat), parseFloat(first.lng)));
}


function showFotos()
{
	google.maps.event.addListener(mapaObj, 'tilesloaded', function() {
		var panoramioLayer = new google.maps.panoramio.PanoramioLayer();
		panoramioLayer.setMap(mapaObj);
		panoramioLayer.setTag('city');
	});
	
	var panoramioLayer = new google.maps.panoramio.PanoramioLayer();
	panoramioLayer.setMap(mapaObj);
	panoramioLayer.setTag('city');
}



function doSearch(obj) {
	scrollToMap(".abas-outros-imovel");
	var ponto = obj.val();
	var searchString = ponto + " próximo a " + enderecoEmp;
	iconBusca = obj.parent().find("img").attr("src");
	
	gLocalSearch.setCenterPoint(mapaObj.getCenter());
	gLocalSearch.execute(searchString);
}
 

function OnLoad()
{
	mapaObj = new google.maps.Map(document.getElementById("map"), {
		center: new google.maps.LatLng(37.4419, -122.1419),
		zoom: 15,
		mapTypeId: 'roadmap'
	});
	
	// Create one InfoWindow to open when a marker is clicked.
	gInfoWindow = new google.maps.InfoWindow;
	google.maps.event.addListener(gInfoWindow, 'closeclick', function() {
		unselectMarkers();
	});

	// Initialize the local searcher
	gLocalSearch = new GlocalSearch();
	gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
}

// Cancel the form submission, executing an AJAX Search API search.
function CaptureForm(searchForm)
{
	gLocalSearch.execute(searchForm.input.value);
	return false;
}

LocalResult.prototype.node = function()
{
	if (this.resultNode_) return this.resultNode_;
	return this.html();
};

// Returns the mapaObj 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 myLatLng = new google.maps.LatLng(me.result_.lat, me.result_.lng);
	var marker = me.marker_ = new google.maps.Marker({
		position: new google.maps.LatLng(parseFloat(me.result_.lat), parseFloat(me.result_.lng)),
		icon: iconBusca, map: mapaObj
	});
	google.maps.event.addListener(marker, "click", function() {
		me.select();
	});
	
	bounds.extend(myLatLng);
	mapaObj.fitBounds(bounds);
	
	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(mapaObj, 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;
}

GSearch.setOnLoadCallback(OnLoad);





function initializePrint(end, rota) {
    
	var uf = end.split("/");
		
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-23.548943, -46.638818);
    var myOptions = {
        zoom: (uf[1] == "RJ" ? 17 : 15),
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);


    geocoder.geocode( { 'address': end}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            marker = new google.maps.Marker({
                map: map,
                icon: "_images/empreendimento.gif",
                position: results[0].geometry.location
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
    
    
    if(rota != "null"){
        directionService = new google.maps.DirectionsService();
        directionsRenderer = new google.maps.DirectionsRenderer({ map: map });
        directionsRenderer.setPanel(document.getElementById("gmaps-lista-enderecos"));
        
        google.maps.event.addListener(directionsRenderer, 'directions_changed', function() {
            if (currentDirections) {
                oldDirections.push(currentDirections);
            }
            currentDirections = directionsRenderer.getDirections();
        });
        tracarRotaPrint(end, rota);
    }
   
   
}

function tracarRotaPrint(end, rota){
    var request = {
        origin: end,
        destination: rota,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    }
        
    // Make the directions request
    directionService.route(request, function(result, status){
        if(status == google.maps.DirectionsStatus.OK){
            directionsRenderer.setDirections(result);
        }
    });
}
