// Object Functions

function setObjectOption(obj, optionName, optionValue)
{
    var option = new Object();
    option[optionName] = optionValue;
    
    if (obj && obj.setOptions)
    {
        obj.setOptions(option);
    }
    
    return JSON.stringify(option);
}

// Map Functions

var map = null;

function getMapType()
{
    var mapType = 0;
    
    switch (map.mapTypeId)
    {
        case google.maps.MapTypeId.ROADMAP:
            mapType = 0;
            break;
        case google.maps.MapTypeId.SATELLITE:
            mapType = 1;
            break;
        case google.maps.MapTypeId.HYBRID:
            mapType = 2;
            break;
    }
    
    return mapType;
}

function setMapType(mapType)
{
    switch (mapType)
    {
        case 0:
            map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
            break;
        case 1:
            map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
            break;
        case 2:
            map.setMapTypeId(google.maps.MapTypeId.HYBRID);
            break;
    }
}

function getCenterCoordinate()
{
    return JSON.stringify(map.getCenter().toJSON());
}

function setCenterCoordinateAnimated(lat, lng, animated)
{
    var latlng = new google.maps.LatLng(lat, lng);
    
    if (animated == true)
    {
        map.panTo(latlng);
    }
    else
    {
        map.setCenter(latlng);
    }
}

// Annotations

var annotations = new Array();

function AnnotationOverlay()
{
    this.marker_ = new google.maps.Marker();
    this.marker_.setAnimation(google.maps.Animation.DROP);
    this.marker_.setDraggable(true);
    this.marker_.setMap(map);
}

AnnotationOverlay.prototype = new google.maps.OverlayView();

AnnotationOverlay.prototype.getMarker = function()
{
    return this.marker_;
}

AnnotationOverlay.prototype.setOptions = function(options)
{
    var marker = this.getMarker();
    
    for (option in options)
    {
        var value = options[option];
        
        if (option == "position")
        {
            marker.setPosition(value);
        }
        else if (option == "draggable")
        {
            marker.setDraggable(value);
        }
    }
}

// Annotation Functions

function addAnnotation(annotation)
{
    if (annotations.indexOf(annotation) != -1)
    {
        return false;
    }
    
    annotations.push(annotation);
    
    if (annotation.getMarker)
    {
        var marker = annotation.getMarker();
        
        google.maps.event.addListener(marker, 'click', function()
        {
            if (window.MCMapView)
            {
                window.MCMapView.annotationScriptObjectClick(annotation);
            }
        });
        
        google.maps.event.addListener(marker, 'rightclick', function()
        {
            if (window.MCMapView)
            {
                window.MCMapView.annotationScriptObjectRightClick(annotation);
            }
        });
        
        google.maps.event.addListener(marker, 'dragstart', function()
        {
            if (window.MCMapView)
            {
                window.MCMapView.annotationScriptObjectDragStart(annotation);
            }
        });
        
        google.maps.event.addListener(marker, 'drag', function()
        {
            if (window.MCMapView)
            {
                window.MCMapView.annotationScriptObjectDrag(annotation);
            }
        });
        
        google.maps.event.addListener(marker, 'dragend', function()
        {
            if (window.MCMapView)
            {
                window.MCMapView.annotationScriptObjectDragEnd(annotation);
            }
        });
        
        marker.setMap(map);
    }
    
    return true;
}

function removeAnnotation(annotation)
{
    if (annotations.indexOf(annotation) == -1)
    {
        return;
    }
    
    annotation.marker_.setMap(null);
    annotation.marker_ = null;
    
    annotations.filter(function(element, index, array)
    {
        return element != annotation;
    });
}

function coordinateForAnnotation(annotation)
{
    return JSON.stringify(annotation.getMarker().getPosition().toJSON());
}

// Easy Geocoding

function showAddress(address)
{
    var geocoder = new google.maps.Geocoder();
    
    geocoder.geocode({'address': address}, function(results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {
            if (results[0])
            {
                var result = results[0];
                var latLng = result.geometry.location;
                
                if (!latLng)
                {
                     return;
                }
                
                setCenterCoordinateAnimated(latLng.lat(), latLng.lng(), true);
                
                if (window.MCMapView)
                {
                    var jsonLatLng = JSON.stringify(latLng.toJSON());
                    
                    window.MCMapView.webviewReportingRightClick(jsonLatLng);
                }
            }
        }
    });
}

// Reverse Geocoding

function reverseGeocode(lat, lng)
{
    var latlng = new google.maps.LatLng(lat, lng);
    var geocoder = new google.maps.Geocoder();
    var MCMapReverseGeocoder = window.MCMapReverseGeocoder;
    
    geocoder.geocode({'latLng': latlng}, function(results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {
            if (results[0])
            {
                MCMapReverseGeocoder.didSucceedWithAddress(JSON.stringify(results[0]));
            }
            else
            {
                MCMapReverseGeocoder.didFailWithError("MKErrorPlacemarkNotFound");
            }
        }
        else if (status == google.maps.GeocoderStatus.ZERO_RESULTS)
        {
            MCMapReverseGeocoder.didFailWithError("MKErrorPlacemarkNotFound");
        }
        else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
        {
            MCMapReverseGeocoder.didReachQueryLimit();
        }
        else
        {
            alert("error");
            MCMapReverseGeocoder.didFailWithError("MKErrorDomain");
        }
    });
    
    return MCMapReverseGeocoder;
}
  
// Geocoding

function geocode(address, lat, lng)
{
    var latlng = null;
    
    if (lat != null && lng != null)
    {
        latlng = new google.maps.LatLng(lat, lng);
    }
    
    var geocoder = new google.maps.Geocoder();
    var request = latlng ? {'address': address, 'latLng': latlng} : {'address': address};
    var MCMapGeocoder = window.MCMapGeocoder;
    
    geocoder.geocode(request, function(results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {
            if (results[0])
            {
                MCMapGeocoder.didSucceedWithResult(JSON.stringify(results[0]));
            }
            else
            {
                MCMapGeocoder.didFailWithError("MKErrorPlacemarkNotFound");
            }
        }
        else if (status == google.maps.GeocoderStatus.ZERO_RESULTS)
        {
            MCMapGeocoder.didFailWithError("MKErrorPlacemarkNotFound");
        } 
        else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
        {
            MCMapReverseGeocoder.didReachQueryLimit();
        }
        else
        {
            alert("error");
            MCMapGeocoder.didFailWithError("MKErrorDomain");
        }
    });
    
    return MCMapGeocoder;
}

// End New API

function initMap(type, lat, lng, zoom, scrollToZoom)
{
    map = null;
    
    try
    {
        var mapTypeId = null;
        
        if (type == 0)
        {
            mapTypeId = google.maps.MapTypeId.ROADMAP;
        }
        else if (type == 1)
        {
            mapTypeId = google.maps.MapTypeId.SATELLITE;
        }
        else if (type == 2)
        {
            mapTypeId = google.maps.MapTypeId.HYBRID;
        }
        
        map = new google.maps.Map(document.getElementById("map"), {
            mapTypeId: mapTypeId,
            center: {lat: lat, lng: lng},
            zoom: zoom,
            disableDefaultUI: true,
            fullscreenControl: false,
            mapTypeControl: false,
            rotateControl: false,
            scaleControl: false,
            streetViewControl: false,
            scrollwheel: scrollToZoom,
            zoomControl: true,
            disableDoubleClickZoom: true,
        });
        
        google.maps.event.addListener(map, 'center_changed', function()
        {
            if (window.MCMapView)
            {
                var jsonLatLng = JSON.stringify(map.getCenter().toJSON());
                
                window.MCMapView.webviewReportingCenterChange(jsonLatLng);
            }
        });
        
        google.maps.event.addListener(map, 'click', function(mouseEvent)
        {
            if (window.MCMapView)
            {
                var jsonLatLng = JSON.stringify(mouseEvent.latLng.toJSON());
                
                window.MCMapView.webviewReportingClick(jsonLatLng);
            }
        });
        
        google.maps.event.addListener(map, 'rightclick', function(mouseEvent)
        {
            if (window.MCMapView)
            {
                var jsonLatLng = JSON.stringify(mouseEvent.latLng.toJSON());
                
                window.MCMapView.webviewReportingRightClick(jsonLatLng);
            }
        });
        
        google.maps.event.addListener(map, 'dblclick', function(mouseEvent)
        {
            if (window.MCMapView)
            {
                var jsonLatLng = JSON.stringify(mouseEvent.latLng.toJSON());
                
                window.MCMapView.webviewReportingDoubleClick(jsonLatLng);
            }
        });
    }
    catch (err)
    {
        if (window.MCMapView)
        {
            window.MCMapView.webviewReportingLoadFailure();
        }
    }
}
