﻿var Geocoder;
var Map;
var HouseIcon;
var RedHouseIcon;
var GreenHouseIcon;
var DestinationAddress;
var Directions = null;
var StartingAddressMarker;
var IsShowingNearbyFacilities = false;

function LoadMap() {
    if (!MapIsValid)
        return;
    if (GBrowserIsCompatible()) {
        Geocoder = new GClientGeocoder(); 
        
        GreenHouseIcon = new GIcon();
        GreenHouseIcon.image = "http://" + Host + "/DesktopModules/SFS_ListingViewerMap/images/greenhaus.gif";
        GreenHouseIcon.shadow = "http://" + Host + "/DesktopModules/SFS_ListingViewerMap/images/greenhaus.gif";
        GreenHouseIcon.imageSize = new GSize(40, 36);
        GreenHouseIcon.shadowSize = new GSize(0, 0);
        GreenHouseIcon.iconAnchor = new GPoint(6, 20);
        GreenHouseIcon.infoWindowAnchor = new GPoint(25, 1);
        
        RedHouseIcon = new GIcon();
        RedHouseIcon.image = "http://" + Host + "/DesktopModules/SFS_ListingViewerMap/images/redhaus.gif";
        RedHouseIcon.shadow = "http://" + Host + "/DesktopModules/SFS_ListingViewerMap/images/redhaus.gif";
        RedHouseIcon.imageSize = new GSize(40, 36);
        RedHouseIcon.shadowSize = new GSize(0, 0);
        RedHouseIcon.iconAnchor = new GPoint(6, 20);
        RedHouseIcon.infoWindowAnchor = new GPoint(25, 1);
        
        HouseIcon = new GIcon();
        HouseIcon.image = "http://" + Host + "/DesktopModules/SFS_ListingViewerMap/images/haus.gif";
        HouseIcon.shadow = "http://" + Host + "/DesktopModules/SFS_ListingViewerMap/images/haus.gif";
        HouseIcon.imageSize = new GSize(40, 36);
        HouseIcon.shadowSize = new GSize(0, 0);
        HouseIcon.iconAnchor = new GPoint(6, 20);
        HouseIcon.infoWindowAnchor = new GPoint(25, 1);

        var center = new GLatLng(MainFacilityLatitude, MainFacilityLongitude);
        
        var canvas = jQuery('#map');
        Map = new GMap2(canvas[0]);
        canvas.debut(function() { 
            Map.checkResize(); 
            Map.setCenter(center, 14);
        });
        
        Map.addControl(new GSmallMapControl());
        Map.addControl(new GMapTypeControl());

        Map.enableContinuousZoom();
        Map.disableScrollWheelZoom();
        Map.setCenter(center, 14);
        Map.setZoom(14);
        GEvent.addListener(Map, "load", ShowAndCenter(MainFacilityAddress, MainFacilityHTML, RedHouseIcon));
    }
}

function RefreshMain() {
    Map.clearOverlays();
    Show(MainFacilityAddress, MainFacilityHTML, RedHouseIcon);   
    
    var xbox = document.getElementById("other_fac_box");
    if (xbox) {
        ShowOtherFacilities(xbox);
    }
}

function AddNearbyFacility(addr, html, point) {
    NearbyFacilityAddresses[NearbyFacilityIdx] = addr;
    NearbyFacilityMarkups[NearbyFacilityIdx] = html;
    NearbyFacilityCoordinates[NearbyFacilityIdx] = point;
    NearbyFacilityIdx++;
}

function Show(address, html, icon) {
    if (UseGoogleGeocoder) 
        GeocodeAndShowAddress(address, html, icon);
    else 
        ShowAddress(address, html, icon);
}

function ShowAddress(address, html, icon) {
    var latlng = new GLatLng(MainFacilityLatitude, MainFacilityLongitude);
    var marker = new GMarker(latlng, icon);
    Map.addOverlay(marker);
    marker.bindInfoWindowHtml(html);
}

function ShowMainFacilityAddress() {
    // If Google can't geocode the facility, use our coordinates --%>
    if (!MainFacilityIsGeocodable) {
        ShowAddress(MainFacilityAddress, MainFacilityHTML, RedHouseIcon);
        var erm = document.getElementById("MapError");
        if (erm) erm.style.display = "block";
        // Set error text
        erm = document.getElementById("MapErrorSpan");
        if (erm) erm.innerHTML = "Cannot precisely geocode this address.  ";
        if (MainFacilityGeocodeError > 0) {
            erm.innerHTML += "The specific error was: ";
            // http://code.google.com/apis/maps/documentation/reference.html#GGeoStatusCode
            if (MainFacilityGeocodeError == 200) erm.innerHTML += "no error.  ";
            else if (MainFacilityGeocodeError == 400) erm.innerHTML += "geocode request could not be parsed.  ";
            else if (MainFacilityGeocodeError == 500) erm.innerHTML += "server errror.  ";
            else if (MainFacilityGeocodeError == 600) erm.innerHTML += "geocode request was empty.  ";
            else if (MainFacilityGeocodeError == 601) erm.innerHTML += "geocode request was empty (missing address).  ";
            else if (MainFacilityGeocodeError == 602) erm.innerHTML += "unknown address.  ";
            else if (MainFacilityGeocodeError == 603) erm.innerHTML += "address unavailable for legal or contractual reasons.  ";
            else if (MainFacilityGeocodeError == 610) erm.innerHTML += "bad map key.  ";
            else if (MainFacilityGeocodeError == 620) erm.innerHTML += "map key query limit exceeded.  ";
            else erm.innerHTML += "unknown error.  ";
        }
        erm.innerHTML += "Approximate location shown.";
    }
}

function GeocodeAndShowAddress(address, html, icon) {
   // alert("Trying to Geocode " + address);
    Geocoder.getLatLng(address,
        function(point) {
            if (point) {
                var marker = new GMarker(point, icon);
                Map.addOverlay(marker);
                //marker.bindInfoWindowHtml(html);
                var infoWOptions = new Object();
                infoWOptions.maxWidth = 400;
                
                marker.bindInfoWindowHtml(html, infoWOptions);
            } else {
                //alert("Google geocode failed");
            }
        });
}

// Show a single facility using SnapCore coordinates
function ShowNearbyFacility(idx) {
    if (!IsShowingNearbyFacilities) return;
    var marker = new GMarker(NearbyFacilityCoordinates[idx], HouseIcon);
    Map.addOverlay(marker);
    marker.bindInfoWindowHtml(NearbyFacilityMarkups[idx]);
}

// Render a single nearby facility, wait for a geocode response, then queue another request
function GeocodeAndShowNearbyFacility(idx) {
    if (!IsShowingNearbyFacilities) return;
    Geocoder.getLatLng(NearbyFacilityAddresses[idx],
        function(point) {
            if (!IsShowingNearbyFacilities) return;
            var marker;
            
            // If the Google geocode was successful, use the Google coordinates,
            // otherwise use the SnapCore coordinates
            if (point) {
                marker = new GMarker(point, HouseIcon);
            } else  {
                marker = new GMarker(NearbyFacilityCoordinates[idx], HouseIcon);
            }
            
            // Add facility marker
            Map.addOverlay(marker);
            var infoWOptions = new Object();
            infoWOptions.maxWidth = 4000;
            marker.bindInfoWindowHtml(NearbyFacilityMarkups[idx], infoWOptions);

            // Geocode next facility
            if ((idx + 1) < NumNearbyFacilities) {
                GeocodeAndShowNearbyFacility(idx + 1);
            }
        });
}

function GeocodeAndShowAddressAndCenter(address, html, icon) {
    if (Geocoder == null) return;
    // We're using getLocations() to find the specific error code if facility isn't geocodable
    Geocoder.getLocations(address, 
        function(status, placemark) {
            if (status && status.Status && status.Status.code)
                MainFacilityGeocodeError = status.Status.code.format("");
        });
    Geocoder.getLatLng(address,
        function(point) {
            if (point) {
                var marker = new GMarker(point, icon);
                Map.addOverlay(marker);
                marker.bindInfoWindowHtml(html);
                Map.panTo(point, 1000);
                MainFacilityIsGeocodable = true;
            } else {
                MainFacilityIsGeocodable = false;
                ShowMainFacilityAddress();
            }
        });
}

function wheel(event){
	var delta = 0;
	if (!event) event = window.event;
	if (event.wheelDelta) {
		delta = event.wheelDelta/120; 
		if (window.opera) delta = -delta;
	} else if (event.detail) {
		delta = -event.detail/3;
	}
	if (delta)
        if (event.preventDefault)
                event.preventDefault();
        event.returnValue = false;
}

// User clicks "Show Nearby Facilities"
function ShowOtherFacilities(element) {
    if (element.checked) {
        IsShowingNearbyFacilities = true;
        var latlng;
        var marker;
    
        NearbyFacilityIdx = 0;
        if (UseGoogleGeocoder) {
            GeocodeAndShowNearbyFacility(NearbyFacilityIdx);
        } else  {
            for (var i = 0; i < NumNearbyFacilities; i++) {
                ShowNearbyFacility(i);
            }
        }
    } else {
        IsShowingNearbyFacilities = false;
        Map.clearOverlays();
        ShowAddress(MainFacilityAddress, MainFacilityHTML, RedHouseIcon);
    }
}

function interrogate(what) {
    var output = '';
    for (var i in what)
        //output += i+ ' = ' + what[i] + '\n';
        output += i+  '\n';
    alert(output);
}

function disable_mousewheel() {
    if (window.addEventListener)
	    window.addEventListener('DOMMouseScroll', wheel, false);

    window.onmousewheel = document.onmousewheel = wheel;
}

function enable_mousewheel() {
    if (window.removeEventListener)
        window.removeEventListener('DOMMouseScroll', wheel, false);
    window.onmousewheel = null;  
    document.onmousewheel = null;
}

function map_mouseover() {
    disable_mousewheel();
}

function map_mouseout() {
    enable_mousewheel();
}

function directions_error() {
    alert("Could not geocode your starting address.  Please enter a more specific starting address.");
}

function directions_addoverlay() {
    var m1 = directions.getMarker(0);
    m1.hide();
    var m2 = directions.getMarker(1);
    m2.hide();
}

function ClearDirections() {
    if (typeof(directions) != "undefined") directions.clear();
}

function FindDirections() {
    var tb = document.getElementById("SrcAddrTextbox");
    if (!tb) return;
    var src_addr = tb.value;
    
    if (src_addr == "") {
        tb.focus();
        tb.style.backgroundColor = "#ffff73";
        setTimeout("AnimateTextbox()", 1);
    }
    
    var iw = Map.getInfoWindow();
    if (!iw) return;
    
    tarPnt = iw.getPoint();
    tarLat = iw.getPoint().lat();
    tarLng = iw.getPoint().lng(); 
    
    var text_dir_div = document.getElementById("TextDirections");
    if (text_dir_div) text_dir_div.style.display == "block";

    var clear_button = document.getElementById("ClearButton");
    if (clear_button) clear_button.style.display == "block";
    
    if (Geocoder == null) return;
    Geocoder.getLatLng(src_addr,
        function(point) {
            if (point) {
                if (typeof(StartingAddressMarker) != "undefined") StartingAddressMarker.hide();
                StartingAddressMarker = new GMarker(point, GreenHouseIcon);
                Map.addOverlay(StartingAddressMarker);
                StartingAddressMarker.bindInfoWindowHtml('<span style="font-size: 1.2em; font-family: Arial, Sans-Serif;">Your Starting Address: <br />' + src_addr + '</span>');
                if (typeof(directions) == "undefined") {
                    directions = new GDirections(Map, text_dir_div);
                    GEvent.addListener(directions, "error", directions_error);
                    GEvent.addListener(directions, "addoverlay", directions_addoverlay);
                }
                directions.clear();
                
                directions.load(src_addr + " to " + tarLat + ", " + tarLng);

            }
        }); 
}

var dir_bgcolor = 115;
var dir_original_bgcolor;
function AnimateBackground() {
    var dir_div = document.getElementById("MapDirectionsInput");
    if (!dir_div) return;
    var hex = (dir_bgcolor-0).toString(16);
    dir_div.style.backgroundColor = "#ffff" + hex;
    if (isIE) dir_bgcolor += 8;
    else dir_bgcolor += 2;
    if (dir_bgcolor < 256) {
        setTimeout("AnimateBackground()", 1);    
    } else {
        dir_bgcolor = 115;
        dir_div.style.backgroundColor = dir_original_bgcolor;
    }
}

var tb_bgcolor = 115;
var tb_original_bgcolor;
function AnimateTextbox() {
    var tb = document.getElementById("SrcAddrTextbox");
    if (!tb) return;
    var hex = (tb_bgcolor-0).toString(16);
    tb.style.backgroundColor = "#ffff" + hex;
    if (isIE) tb_bgcolor += 2;
    else tb_bgcolor += 2;
    if (tb_bgcolor < 256) {
        setTimeout("AnimateTextbox()", 1);    
    } else {
        tb_bgcolor = 115;
        tb.style.backgroundColor = tb_original_bgcolor;
    }
}

function FocusTextbox() {
    var tb = document.getElementById("SrcAddrTextbox");
    if (tb) tb.focus();
}

function DisplayDirections() {
    var dir_div = document.getElementById("MapDirectionsInput");
    if (dir_div) {
        if (dir_div.style.display == "block") {
            FindDirections()
        } else {
            dir_div.style.display = "block";
            dir_original_bgcolor = dir_div.style.backgroundColor;
            dir_div.style.backgroundColor = "#ffff73";
            setTimeout("AnimateBackground()", 1);
            var tb = document.getElementById("SrcAddrTextbox");
            if (tb) tb.focus();
        }
    }
}

    
function EnableKeyboardAddressSubmit(element) {
    if (!element) return;
    if (/Apple/.test(navigator.userAgent)) {
        window.onkeydown = window.onkeyup = function(kbd) {
            if (kbd.keyCode == 13) {
                FindDirections();
                return false;
            }
        }
        
    } else if (isIE) {
        element.onkeypress = function() {
            if (window.event.keyCode == 13) {
                FindDirections();
                return false;
            }
        }
    } else {
        window.onkeydown = function(kbd) {
            if (kbd.keyCode == 13) {
                FindDirections();
                return false;
            }
        }
    }
}

function DisableKeyboardAddressSubmit(element) {
    if (!element) return;
    if (/Apple/.test(navigator.userAgent)) {
        window.onkeydown = window.onkeyup = null;
    } else if (isIE) {
        element.onkeypress = null;
    } else { 
        window.onkeydown = null;
    }
}

