﻿
//icon.image = "http://www.google.com/mapfiles/arrow.png";
//icon.shadow = "http://www.google.com/mapfiles/arrowshadow.png";
//icon.iconSize = new GSize(39, 34);
//icon.shadowSize = new GSize(45, 34);
//icon.iconAnchor = new GPoint(10, 34);

function hotelIcon()
{
    var icon = new GIcon(G_DEFAULT_ICON);
    icon.image = "/images/googleIcons/rjpointer.png";
    icon.iconSize = new GSize(23, 35);
    icon.shadowSize = new GSize(46,34);
    return icon;
}

function usePointFromPostcode(postcode, callbackSuccess , callbackFail ) {
	var localSearch = new GlocalSearch();
	localSearch.setCenterPoint("UK");
	localSearch.setSearchCompleteCallback(null, 
		function() {
			
			if (localSearch.results[0])
			{		
				var resultLat = localSearch.results[0].lat;
				var resultLng = localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				point.postcode = localSearch.results[0].title;
				callbackSuccess( point );
			}else{
				callbackFail();
			}
		});	
		
	localSearch.execute(postcode);
}

function addDirections( startPoint , endPoint , map , output , startIcon , endIcon )
{
    if( typeof output == "string") output = document.getElementById(output);
    
    if( !map.dir )
    {
        map.dir = new GDirections(map,output);
        GEvent.addDomListener(map.dir, "load", function() {
//            alert( (map.dir.getDistance().meters/1000)/1.6 + " miles");
            map.clearOverlays();
            $(output).slideDown();
            if( endIcon )
                for(var i in endIcon )
                    this.getMarker(1).getIcon()[i] = endIcon[i];
        });

        GEvent.addDomListener(map.dir, "error", function() {
            $(output).slideUp();
            $(".googleFindDirections").append('<p class="validateError">Sorry, but directions to this hotel could not be retrieved.</p>');
        });
    }
    map.dir.clear();
    map.dir.load( startPoint + " to " + endPoint );
}

function googleLoad()
{
	var el = this;
	var gLat = el.getAttribute("lat");
	var gLong = el.getAttribute("long");
	if( (!gLat && !gLong) ) return;
	
	var map = new GMap2( el );
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setMapType(G_NORMAL_MAP);
    map.enableContinuousZoom();
	var point = new GLatLng( gLat, gLong );
	setPoint( point , map );

    $("#postcode").keypress(function(e){
        if(e.keyCode == 13 ) {$(".googleFindDirections :submit").click();return false;}
    });

    $(".googleFindDirections :submit").click( function(e) {
        var postcode = $.trim($("#postcode").val());
        if( !postcode )
        {
            $(".googleFindDirections").append('<p class="validateError">Please enter an address</p>');
            return false;
        }
        $(".googleFindDirections .validateError").remove();
        usePointFromPostcode( postcode, function( p )
        {
            if( !document.getElementById("googleMapDirections") )
                $(el).after('<div id="googleMapDirections" class="googleMapDirections" />').next().hide();
            addDirections(p.lat() +","+p.lng() , gLat + "," + gLong , map , "googleMapDirections" , null,hotelIcon() );
        },function() {
                $(".googleFindDirections").append('<p class="validateError">Sorry, but the starting point could not be found.</p>');
        });
        
        if (e && e.preventDefault) e.preventDefault();
        return false;
    });
	
}

function ResetButton(){}

ResetButton.prototype = new GControl();

ResetButton.prototype.initialize = function(map) {
    var container = $('<div class="btnGoogleReset"><div>Reset Map</div></div>').get(0);
    GEvent.addDomListener(container, "click", function() {
        map.isReset = true;
        map.returnToSavedPosition();
        map.closeInfoWindow();
        map.removeControl( map.reset );
    });

    map.getContainer().appendChild(container);
    return container;
}

ResetButton.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 25));
}

function addMapReset( map )
{
    map.savePosition();
    map.reset = new ResetButton();
    var zoomLevel = map.getZoom();
    var center = map.getCenter();

    function changeMapPos()
    {
        if( (map.getZoom() != zoomLevel || map.getCenter() != center) && !map.isReset )
        {
            map.addControl( map.reset );
        }
        map.isReset = null;
    }

    GEvent.addListener( map , "zoomend" , changeMapPos );
    GEvent.addListener( map , "moveend" , changeMapPos );
}

function loadSearchResultsMap()
{
    $(".searchResultsMap h2").toggle(
        // open the map
        function() {
            
            // check to see if the map has been loaded yet and show it
            if( $(".searchResultsMap #googleMap").length )
            {
                $(this).addClass("open");
                $(".searchResultsMap #googleMap").slideDown("slow");
                $(".result h3 img").show();
            }
            // otherwise create and setup the googlemap, then show it
            else
            {
                $(".searchResultsMap").append('<div id="googleMap" class="googleMap mapOffscreenLoad"/>');
                var map = new GMap2( $("#googleMap").css("width","auto").get(0) );

                GEvent.addListener( map , "load" , function() {
                    setTimeout( '$("#googleMap").removeClass("mapOffscreenLoad").slideDown("slow").prev().addClass("open")' , 1);
                    if( loadGoogleJS.loadHotel )
                    {
                        setTimeout( loadGoogleJS.loadHotel , 100 );
                    }
                });
                
                var bounds = new GLatLngBounds();
	            map.addControl(new GLargeMapControl());
	            map.addControl(new GMapTypeControl());
                map.setCenter( new GLatLng( 0 , 0 ) , 0 );
                map.enableContinuousZoom();
                map.setMapType(G_NORMAL_MAP);
                $("[hotelCoords]").each( function(e) {
                    var result = $(this);
                    var link = result.find(".actions p a.link,.linkList li:first a");
                    var hotelName = result.find(".hotelName").text();
                    if( link.length )
                    {
                        link = '<p class="link"><a href="' + link.eq(0).attr("href") + '">' + hotelName + ' home page</a></p>';
                    }
                    else
                    {
                        link = "";
                    }
                    var hotelCoords = result.attr("hotelCoords").split(",");
                    var point = new GLatLng( hotelCoords[0],hotelCoords[1]);
                    var iIcon = new GIcon(G_DEFAULT_ICON);
                    iIcon.image = "/images/googleIcons/marker" + (e+1) + ".png";
                    var hotel = new GMarker( point,iIcon );
                    
                    GEvent.addListener(hotel, "click", function() {
                        hotel.openInfoWindowHtml( '<div class="hotelInfoWindow"><img src="/images/rjhelplogo.gif" alt="Ramada Jarvis Logo" height="20"/><br/><h5>' + hotelName + '</h5><h6>' +result.find(".hotelAddress").html() + '</h6>' + link + "</div>");
                    });
                    
                    map.addOverlay( hotel );
                    bounds.extend( point );
                    $(this).find("h3:first").append('<img src="/images/googleIcons/marker' + (e+1) + '_circle.gif" alt="Go to map point ' + ( e+1 ) + '"/>').find(":last")
                        .click( function() {
                            if( $(".searchResultsMap h2").offset().top < getScrollXY()[1] )
                                $('html,body').animate({scrollTop: $(".searchResultsMap h2").offset().top - 20 });
                            map.setCenter( point );
                            map.setZoom(14);
                            GEvent.trigger( hotel , "click");
                        });
                });  

                map.setZoom( $("[hotelCoords]").length > 1 ? map.getBoundsZoomLevel(bounds) : 14);
                map.setCenter(bounds.getCenter());
                addMapReset( map );

            }
            return false;
        // close the map
        }, function() {
            $(this).removeClass("open");
            $("#googleMap").slideUp("slow");
            $(".result h3 img").hide();
            return false;
        });
    $(".searchResultsMap h2").click();
}

function loadThingsToDo()
{
    var hotelCoords = $("[hotelCoords]").attr("hotelCoords").split(",");
    var hotelName = $(".thingsToDoEvents").attr("hotelName");
    var coords = $(".thingsToDoEvents .imageBox[lat][long]");
    $(".thingsToDoPage").prepend('<div id="googleMap" class="googleMap"/>');

    var map = new GMap2( $(".googleMap").css("width","auto").get(0) );
    var bounds = new GLatLngBounds();
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
    map.setMapType(G_NORMAL_MAP);
    map.enableContinuousZoom();
    // add hotel marker
    var point = new GLatLng( hotelCoords[0],hotelCoords[1]);
    map.setCenter( point , 13 );
    var hotel = new GMarker( point,hotelIcon() );
    map.addOverlay( hotel );
    bounds.extend( point );

    GEvent.addListener(hotel, "click",
        function() {
            hotel.openInfoWindowHtml( '<img src="/images/rjhelplogo.gif" alt="Ramada Jarvis Logo"/><br/><br/><h4>' +hotelName + '</h4>' );
        }
    );

    var coordTest = {};
    var markers = {};

    coords.each( function() {
        var gLat = $(this).attr("lat");
        var gLong = $(this).attr("long");
        var point = new GLatLng( gLat , gLong );
        var html = '<p style="width:170px;" class="link">' + $(this).find("h3").html() + '</p>';
        
        $(this)
            .find("p:last")
            .append('<span class="link">Show on map</span>')
            .find(":last")
            .click( function() {
                var wowEvent = $(this).parents(".imageBox:first");
                map.closeInfoWindow();
                var m = wowEvent.data("marker");
                m.openInfoWindowHtml( m.html[ wowEvent.data("markerPos")] );
                $('html,body').animate({scrollTop: $("#googleMap").offset().top - 20 });
            });

        if( markers[ gLat + "," + gLong ] )
        {
            markers[ gLat + "," + gLong ].html.push(html);
            $(this).data( "marker" , markers[ gLat + "," + gLong ] );
            $(this).data( "markerPos" , markers[ gLat + "," + gLong ].html.length -1 );
            return true;
        }

        var marker = markers[ gLat + "," + gLong ] = new GMarker(point);
        marker.html = [html];
        GEvent.addListener(marker, "click",
            function() {
                marker.openInfoWindowHtml(marker.html.join(""));
            }
        );

        $(this).data( "marker" , markers[ gLat + "," + gLong ] );
        $(this).data( "markerPos" , markers[ gLat + "," + gLong ].html.length -1 );

        map.addOverlay( marker );
        bounds.extend( point );
    });
    map.setZoom( coords.length > 1 ? map.getBoundsZoomLevel(bounds) : 13);
    map.setCenter(bounds.getCenter());
    addMapReset( map );
    
}

function setPoint( point , map )
{
	map.setCenter( point , 14 );
	var marker = new GMarker(point,hotelIcon());
	map.addOverlay(marker);
}

$( function() {
	if (GBrowserIsCompatible())
	{ 
        $(".googleMap").css("width","auto").each( googleLoad )
        if( $(".thingsToDoEvents .imageBox").length )
        {
            loadThingsToDo();
        }

        if( $(".result[hotelCoords]").length )
        {
            loadSearchResultsMap();
        }
    }
});

$(window).unload(GUnload);