﻿//<![CDATA[

var map = null;
var geocoder = null;
var hotelDeLaVille;
var direction;
var largeControl = new GLargeMapControl();
var overviewControl = new GOverviewMapControl();

function load() {
  
}
function showAddress(address,zoom) {
if (geocoder)
{
	geocoder.getLatLng(
		address,
	  	function(point) 
	  	{
			if (!point) 
			{
				if (address == '' || address == ' ')
				{
					alert('Please, insert an address');
				}
				else
				{
					alert(address + " not found");
				}
			} 
			else 
			{
			    var distanza = Math.round(point.distanceFrom(hotelDeLaVille) / 1000);
			    //$('div#distanza').html('You are <strong>' + distanza + ' Km</strong> away from us');
			    addYouAreHerePoint(point);
			    resetCenter(hotelDeLaVille,point);
			    showDirection(point);
			}
		}
	);
	geocoder.getLocations(address, addGeocodeAddress);
    }
}
function addGeocodeAddress(response) {
  if (!response || response.Status.code != 200) {
    //alert("Sorry, we were unable to geocode that address");
  } else {
    place = response.Placemark[0];
	$('#geocode').html(place.address);
  }
}
function getLocations (query)
{
    geocoder.getLocations(query, addResults);
}
function addResults(response)
{
    if (!response || response.Status.code != 200) 
    {
        //alert("Sorry, we were unable to geocode that address");
    } 
    else 
    {
        //$("#suggerimenti").show();
        $("#suggerimenti").slideDown("slow");
	    var numPlacemarks = response.Placemark.length;
	    //if (numPlacemarks > 15) numPlacemarks = 15;
	    arrPlaceMarks = new Array();
	    for (var i=0; i<numPlacemarks; i++) { 
		    arrPlaceMarks[i] = response.Placemark[i].address;
	    }
	    //xajax_updateAdressList(arrPlaceMarks);
	    var len = arrPlaceMarks.length;
	    var output = '';
	    for (i=0;i<len;i++)
	    {
	        output += '<a href="javascript:void(0)" onclick="insertLocation(\'' + arrPlaceMarks[i] + '\')">' + arrPlaceMarks[i] + '</a><br />';
	    }
	    $('#suggerimenti').html(output);
	    //$('suggerimenti').show("slow");
    }
}
function insertLocation(location)
{
    //alert(location);
    $("#suggerimenti").slideUp("fast");
    $('#whereyouare').children('input').val(location);
    //showAddress(location,12);
}
function showDirection(from)
{
    $('#errore').html('');
    setDirections(from.lat() + ',' + from.lng(),hotelDeLaVille.lat() + ',' + hotelDeLaVille.lng(),'en_US');
}
function setDirections(fromAddress, toAddress, locale) 
{
    direction.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
    /*for (i=0; i< markers.length; i++ ) 
    {
         alert(markers[i]);
    }*/

}


function resetCenter(point1,point2)
{
    if (point1.lng() <= point2.lng())
    {
        mySpace = new GLatLngBounds(point1,point2); 
        var newZoom = map.getBoundsZoomLevel(mySpace);
        var newCenter = mySpace.getCenter();
        map.setCenter(newCenter,newZoom ); 
    }
    else
    {
        mySpace = new GLatLngBounds(point2,point1); 
        var newZoom = map.getBoundsZoomLevel(mySpace);
        var newCenter = mySpace.getCenter();
        map.setCenter(newCenter,newZoom );
    }
}

function addYouAreHerePoint(point)
{
    map.clearOverlays();
    var baseImage = new GIcon();
    baseImage.image = "/common/images/location/youarehere.gif";
    baseImage.iconSize = new GSize(20, 20);
    baseImage.iconAnchor = new GPoint(10, 10);
    baseImage.infoWindowAnchor = new GPoint(0, 0);
    pin = new GMarker(point, baseImage);
    map.addOverlay(pin);
}

function changeZoomLevel(level)
{
    map.setZoom(level);
}

function changeZoomStatus()
{
    var zoom = map.getZoom();
    var isSelected;
    $('#zoom .zoomlevel').each(function() {
        isSelected = false;
        zoomNum = parseInt($(this).children('img').attr('id'));
        numeroFoto = zoomNum + 1;
        if (zoomNum < zoom)
        {
            $(this).html('<img src="/common/images/location/z' + numeroFoto + '_on.gif" onclick="changeZoomLevel(' + zoomNum + ');" alt="zoom level ' + zoomNum + '" class="before" id="' + zoomNum + '" />');
            $(this).css('cursor','pointer');
        }
        else if (zoomNum == zoom)
        {
            $(this).html('<img src="/common/images/location/selected/z' + numeroFoto + '_off.gif" alt="actual zoom" class="no_rollover" id="' + zoomNum + '" />');
            $(this).css('cursor','default');
        }
        else
        {
            $(this).html('<img src="/common/images/location/z' + numeroFoto + '_off.gif" onclick="changeZoomLevel(' + zoomNum + ');" alt="zoom level ' + zoomNum + '" class="after" id="' + zoomNum + '" />');
            $(this).css('cursor','pointer');
        }
    }); 
    
    $('#zoom .zoomlevel img.before:not(.no_rollover)').each(function() {
        $(this).mouseover( function(){ $(this).attr("src", $(this).attr("src").split('_on').join('_off')) } );
        $(this).mouseout( function(){ $(this).attr("src", $(this).attr("src").split('_off').join('_on')) } );
    }); 
    $('#zoom .zoomlevel img.after:not(.no_rollover)').each(function() {
        $(this).mouseover( function(){ $(this).attr("src", $(this).attr("src").split('_off').join('_on')) } );
        $(this).mouseout( function(){ $(this).attr("src", $(this).attr("src").split('_on').join('_off')) } );
    }); 
}

function resetMapPosition()
{
    map.returnToSavedPosition();
}

function addHotelMarker()
{
    var baseImage = new GIcon();
    baseImage.image = "/common/images/location/hdv_marker.gif";
    baseImage.iconSize = new GSize(62, 90);
    baseImage.iconAnchor = new GPoint(31, 90);
    baseImage.infoWindowAnchor = new GPoint(0, 0);
    pin = new GMarker(hotelDeLaVille, baseImage);
    map.addOverlay(pin);
}

$().ready(function(){
    if (GBrowserIsCompatible()) 
    {
        map = new GMap2(document.getElementById("map"));
        hotelDeLaVille = new GLatLng(45.592717, 9.271838);
        directionsPanel = document.getElementById("itinerario");
        direction = new GDirections(map,directionsPanel);
        GEvent.addListener(direction, "error", handleErrors);
        GEvent.addListener(direction, "load", loadedDirections);
        map.setCenter(new GLatLng(45.578724,9.274864), 12);
        map.savePosition();
        //map.enableScrollWheelZoom();
        map.addControl(new GMapTypeControl());
        geocoder = new GClientGeocoder();
        addHotelMarker();
        GEvent.addListener(map, "moveend", function() 
        {
		    //alert('moveend');
	    });
	    GEvent.addListener(map, "zoomend", function() 
	    {
		    //alert('zoomend');
		    changeZoomStatus();
	    });
	}

    $("div#itineraries").hide();
    
    $('div#t').click(function() {
        map.panDirection(0,1);
    });
    $('div#b').click(function() {
        map.panDirection(0,-1);
    });
    $('div#r').click(function() {
        map.panDirection(-1,0);
    });
    $('div#l').click(function() {
        map.panDirection(1,0);
    });
    $('div#tl').click(function() {
        map.panDirection(1,1);
    });
    $('div#tr').click(function() {
        map.panDirection(-1,1);
    });
    $('div#bl').click(function() {
        map.panDirection(1,-1);
    });
    $('div#br').click(function() {
        map.panDirection(-1,-1);
    });
    $('.zoomin').click(function() {
        map.setZoom(map.getZoom() + 1);
    });
    $('.zoomout').click(function() {
        map.setZoom(map.getZoom() - 1);
    });
    $('#search a').click(function() {
        $('#search').addClass("selected");
        $('#itineraries').removeClass("selected");
        $('#itinerario').hide();
        $('#whereyouare').show();
        $('#distanza').show();
        $('#errore').show();
        $('#geocode').show();
    });
    $('#itineraries a').click(function() {
        $('#itineraries').addClass("selected");
        $('#search').removeClass("selected");
        $('#itinerario').show();
        $('#whereyouare').hide();
        $('#distanza').hide();
        $('#errore').hide();
        $('#suggerimenti').hide();
        $('#geocode').hide();
    });
    /*$('#whereyouare').keyup( function() {
        //alert($(this).children('input').attr('value').length);
        if ($(this).children('input').attr('value').length > 2)
        {
            //alert($(this).children('input').attr('value'));
            getLocations($(this).children('input').attr('value'));
        }
        else
        {
            $("#suggerimenti").slideUp("fast");
        }
    });*/
 
    changeZoomStatus();
    
});

function loadedDirections()
{
    //$("div#itineraries").fadeIn("slow");
    var marker = direction.getMarker(1);
    icon = marker.getIcon();
    icon.image = "/common/images/location/hdv_marker.gif";
    icon.iconSize = new GSize(62, 90);
    icon.iconAnchor = new GPoint(31, 90);
    icon.infoWindowAnchor = new GPoint(0, 0);
}

function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
   showAddress(myfield.value,12);
   return false;
   }
else
   return true;
}

function findDirectionButton()
{
    var location = $('#whereyouare input#address').val() + ' ' + $('#whereyouare input#city').val();
    showAddress(location,12);
}

function handleErrors()
{
    if (direction.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: " + gdirections.getStatus().code);
    else if (direction.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: " + gdirections.getStatus().code);
	
    else if (direction.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: " + gdirections.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
 
    else if (direction.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: " + gdirections.getStatus().code);
	
    else if (direction.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + gdirections.getStatus().code);
	
    else
    {
        //alert("It's not possible to trace directions between the specified addresses.");
        $('#errore').html('Sorry, it\'s not possible to trace a route');
        addHotelMarker();
    }

}



function enlargeMap()
{
    $('div#map').css('width','958px');
    $('div#map').css('height','480px');
    $('div#map').css('position','relative');
    $('div#map').css('left','-395px');
    $('div.corner').each( function() {
        $(this).css("visibility","hidden");
    });
    $('#zoom').hide();
    map.checkResize();
    map.addControl(largeControl);
    map.addControl(overviewControl);
    map.enableScrollWheelZoom();
    $('div#header div.scheda2').html('<a href="javascript:void(0)" onclick="reduceMap()">Reduce Map</a>');
    $('div.menu_interno').css('visibility','hidden');
}
function reduceMap()
{
    $('div#map').css('width','558px');
    $('div#map').css('height','390px');
    $('div#map').css('position','relative');
    $('div#map').css('left','0px');
    $('div.corner').each( function() {
        $(this).css("visibility","visible");
    });
    $('#zoom').show();
    map.checkResize();
    map.removeControl(largeControl);
    map.removeControl(overviewControl);
    map.disableScrollWheelZoom();       
    $('div#header div.scheda2').html('<a href="javascript:void(0)" onclick="enlargeMap()">Enlarge Map</a>');
    $('div.menu_interno').css("visibility","visible").hide().fadeIn();
}

//]]>