﻿//============================================================
//SCRIPTS DO GOOGLE MAPS
//============================================================
var  map, addressMarker, gdir, fromAddress, toAddress;

function initialize() {
    if (GBrowserIsCompatible()) {
        //-->Gera o Google Maps
        var mapa = new GMap2(document.getElementById("mdlgeowppr01"));
        var geocoder = new GClientGeocoder();
        var address = $('.conteinergeo01 address').text();
        //alert(address);

        geocoder.getLatLng(
        address,
            function(point) {
                if (!point) {
                    alert("Endereço não encontrado para gerar o mapa!");
                } else {
                    mapa.setCenter(point, 13);
                    var marker = new GMarker(point);
                    mapa.addOverlay(marker);
                    marker.openInfoWindowHtml("<b>Colégio CEST</b><br/><br/>" + address);
                    mapa.addControl(new GLargeMapControl());
                }
            }
        );

        //-->Gera o Google Directions
        geocoder.getLatLng(
        address,
            function(point) {
                if (!point) {
                    alert("Endereço não encontrado para gerar a direção para o mapa!");
                } else {

                    var defaultZoomLevel = 14;
                    //end settings

                    //setup elements
                    map = new GMap2(document.getElementById("map_canvas_ipatinga"));
                    gdir = new GDirections(map, document.getElementById("directions_ipatinga"));

                    //error handler
                    //GEvent.addListener(gdir, "error", handleErrors);

                    //set company marker
                    var companyMarker = new GMarker(point);

                    //set map center
                    map.setCenter(point, defaultZoomLevel);
                    map.addOverlay(companyMarker);    
                    
                }
            }
        );  
    }
}

/*
**
* Looks up the directions, overlays route on map,
* and prints turn-by-turn to #directions.
*/

function overlayDirections() {
    fromAddress = document.getElementById("txtbegin_ipatinga").value;
	toAddress = $('.conteinergeo01 address').text().replace(", Centro","");
	//alert(toAddress);
	
    gdir.load("from:" + fromAddress + " to: " + toAddress, { "locale": "pt_BR" });
}

$('#button_rota_ipatinga').live('click',function(e) {
  if ($('#txtbegin_ipatinga').val() != ""){
    e.preventDefault();
    overlayDirections();
    $('.imprimir').show();
  }
});

/*
**
* Wrapper function to create/return a marker object
* with custom image
*/
function createMarker(latlng, imageURL, imageSize) {

    var marker = new GIcon(G_DEFAULT_ICON);
    marker.image = imageURL;
    marker.iconSize = imageSize;

    var options = { icon: marker };

    return new GMarker(latlng, options);

}
/*
**
* Display error to user
*
*/
function handleErrors() {
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
    else alert("An unknown error occurred.");
}

$(document).ready(function(){
  $('.chamarlocalizacao').click(function(){
$('.conteinergeo01 address').text($(this).parent().children('p').text());

  makeOverlay(function(){
	 $(".mdlgnr_geo").animate({'top':'50%'}, 'fast');
	 initialize();
	 $(".clsmdlgnerico_geo").click(function(){
		 $(".mdlgnr_geo").animate({'top':'-1000px'}, 'fast', function() {
          removeOverlay();
		  $('.conteinergeo02').animate({'left':'0'}, 'fast',function(){
            $(".bntmdlvltmapa").fadeOut('fast', function(){
              $(".btnmdlobtrota").fadeIn('fast');
			  $('#txtbegin_ipatinga').val("");
			  $('#directions_ipatinga').empty();
			  });
			});
		  })
	 })
   });
  });
  
  
  //FECHA MODAL LOCALIZACAO
  // ROLA WRAPPER NA POSICAO WRAPPER GERAR ROTA
  $(".btnmdlobtrota").click (function () {
	  $('.conteinergeo02').animate({'left':'-790px'}, 'fast');
	  $(".btnmdlobtrota").fadeOut('fast', function(){$(".bntmdlvltmapa").fadeIn('fast')});
	});
  
  //VOLTA WRAPPER BOXES NA POSICAO INCIAL
  $(".bntmdlvltmapa").click (function () {
	$('.conteinergeo02').animate({'left':'0'}, 'fast');
	$(".bntmdlvltmapa").fadeOut('fast', function(){$(".btnmdlobtrota").fadeIn('fast')});
	})






})

						



//============================================================
//SCRIPT PARA CARREGAR ASSINCRONAMENTE O MAPA DO GOOGLE MAPS
//============================================================
function carregaMapa(idMapa, isAba) {
    $.ajax({
        url: 'mod/retornaMapa.ashx',
        dataType: 'html',
        type: 'post',
        data: { id: idMapa },
        beforeSend: function() {
            $('#carregando').fadeIn();
            $('#contentMapa').empty();
        },
        success: function(data) {
            $('#contentMapa').append(data).hide().fadeIn();
            initialize();
        },
        complete: function() {
            $('#carregando').fadeOut();
            if (isAba != true) {
                makeOverlay(function() { $('#localizacaoContainer').animate({ 'top': '50%' }, 'fast') });
                marcaAbaAtiva(idMapa);
            }
        },
        timeout: 60000
    });
}


