﻿var _ctrlIdMapDiv = null;
var _ctrlIdLatIn = null;
var _ctrlIdLngIn = null;
var _jsClearLocation = null;
var _map = null;
var _marker = null;

function initMap(ctrlIdMapDiv, ctrlIdLatIn, ctrlIdLngIn, urlMarkerIcon, urlMarkerIconShadow, locationLat, locationLng, initZoom, jsClearLocation) {
    _ctrlIdMapDiv = ctrlIdMapDiv;
    _ctrlIdLatIn = ctrlIdLatIn;
    _ctrlIdLngIn = ctrlIdLngIn;
    _initZoom = initZoom;
    _jsClearLocation = jsClearLocation;

    _map = new GMap2($get(_ctrlIdMapDiv));
    var lat = null;
    var lng = null;
    if (google.loader.ClientLocation && google.loader.ClientLocation.latitude && google.loader.ClientLocation.longitude) {
        lat = google.loader.ClientLocation.latitude;
        lng = google.loader.ClientLocation.longitude;
    }
    else {
        lat = locationLat;
        lng = locationLng;
    }
    _map.setCenter(new GLatLng(lat, lng), _initZoom);
    _map.addControl(new GSmallMapControl());

    // Create marker
    var markerIcon = new GIcon(G_DEFAULT_ICON);
    markerIcon.image = urlMarkerIcon;
    markerIcon.shadow = urlMarkerIconShadow;
    markerIcon.iconSize = new GSize(20, 34);
    markerIcon.shadowSize = new GSize(37, 34);
    markerIcon.iconAnchor = new GPoint(9, 34);
    markerIcon.infoWindowAnchor = new GPoint(9, 2);
    _marker = new GMarker(new GLatLng(lat, lng), { icon: markerIcon, draggable: true });
    _map.addOverlay(_marker);
    GEvent.addListener(_marker, "dragend", onMarkerDragEnd);

    // Show initial lat lng
    displayLatLng(new GLatLng(lat, lng), false, true);
}

function onMarkerDragEnd() {
    eval(_jsClearLocation); // Clear user searched for location
    displayLatLng(_marker.getLatLng(), false, true);
}

function displayLatLng(latLng, moveMarker, refreshLatLng) {
    if (moveMarker) _marker.setLatLng(latLng);
    _map.panTo(latLng);
    if (refreshLatLng) {
        $get(_ctrlIdLatIn).value = latLng.lat();
        $get(_ctrlIdLngIn).value = latLng.lng();
    }
    ClearMapHtml();
}

function IsNumeric(input) {
    return (input - 0) == input && input.length > 0;
}

function ValidateIsNumeric(source, args) {
    args.IsValid = IsNumeric(args.Value);
}