var marker = null;
var markers = [];
var geocoder = null;
var map = null;
var mapOpen = false;


// jQuery page load function
$(document).ready(function() {
    if ($("#vendor_map_detail").length > 0) {
        Geocode_calculate();

        $('.SetLatLonButton').click(function() {
                Geocode_calculate();
        });
    }

    if ($("#vendor_map_canvas").length > 0) {

        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndPageChangeRequestHandler);

        Geocode_calculate();
    }
});

function Geocode_calculate() {
    geocoder = new GClientGeocoder();
    if ($("#vendor_map_detail").length > 0) {
        map = new GMap2(document.getElementById('vendor_map_detail'), { size: new GSize(300, 300) });
    }
    else {
        map = new GMap2(document.getElementById('vendor_map_canvas'), { size: new GSize(300, 300) });
    }

    map.addControl(new GSmallMapControl);
    map.disableScrollWheelZoom();

    var value = $(".latlonTextBox").val();

    var point = new GLatLng(44.565795, -123.271837);
    if (value.length > 0) {
        var p = value.split(',');
        var lat = parseFloat(p[0]);
        var lon = parseFloat(p[1]);

        point = new GLatLng(lat, lon);

        showSaved(point);
    }
    else {
        var address = $(".geocodeTextBox").val();

        if (address.length > 0) {
            showAddress(address);
        }
    }
}

function EndPageChangeRequestHandler(sender, args) {
    Geocode_calculate();
}

function displayPointVendor(marker) {
    var point = marker.getLatLng();
    $(".latlonTextBox").val(point.toUrlValue(6));
    $("#hiddenLatLng input[id$='mapLat']").val(point.lat());
    $("#hiddenLatLng input[id$='mapLng']").val(point.lng());
}

function showSaved(point) {
    if ($("#vendor_map_detail").length > 0) {
        var marker = new GMarker(point);
    }
    else {
        var marker = new GMarker(point, { draggable: true });
        GEvent.addListener(marker, "dragend", function() {
            displayPointVendor(marker); 
            });
    }
    
    map.setCenter(point, 13);
    map.addOverlay(marker);
}

function showAddress(address) {
    geocoder.getLatLng(
       address,
    function(point) {
      if (point) {
	    var marker = new GMarker(point, {draggable: true});

	    GEvent.addListener(marker, "dragend", function() {
        displayPointVendor(marker); 
            });

        map.setCenter(point, 13);
        map.addOverlay(marker);

	    $(".latlonTextBox").val(point.toUrlValue(6));
	    $("#hiddenLatLng input[id$='mapLat']").val(point.lat());
	    $("#hiddenLatLng input[id$='mapLng']").val(point.lng());
    	}
    }
  );
}

