@import <AppKit/CPView.j>
@import "MKMapScene.j"
@import "MKMarker.j"
@import "MKLocation.j"
@import "MKPolyline.j"

/* a "class" variable that will hold the domWin.google.maps object/"namespace" */
var gmNamespace = nil;

MKLoadingMarkupWhiteSpinner = @"<div style='position: absolute; top:50%; left:50%;'><img src='Frameworks/MapKit/Resources/spinner-white.gif'/></div>";
MKLoadingMarkupBlackSpinner = @"<div style='position: absolute; top:50%; left:50%;'><img src='Frameworks/MapKit/Resources/spinner-black.gif'/></div>";

/*
@implementation CPWebView(ScrollFixes) {
    - (void)loadHTMLStringWithoutMessingUpScrollbars:(CPString)aString
    {
        [self _startedLoading];

        _ignoreLoadStart = YES;
        _ignoreLoadEnd = NO;

        _url = null;
        _html = aString;

        [self _load];
    }
}
@end
*/


@implementation MKMapView2 : CPWebView {
    CPString        _apiKey;
    DOMElement      _DOMMapElement;
    JSObject        _gMap               @accessors(property=gMap);
    MKMapScene      _scene              @accessors(property=scene);
    BOOL            _mapReady;
    BOOL            _googleAjaxLoaded;
    id              delegate            @accessors;
    BOOL            hasLoaded;
    MKLocation      _center;
    CPString        _centerName;
    int             _zoomLevel;
    int				_someVari;
    CPView          _loadingView @accessors(property=loadingView);
}


- (void) loadHTMLStringWithoutMessingUpScrollbars:(CPString)aString {
        [self _startedLoading];
        _ignoreLoadStart = YES;
        _ignoreLoadEnd = NO;
        _url = null;
        _html = aString;
        [self _load];
}


- (void) addEvent:(id)_anEvent aFunctionToCall:(CPString)_aFunct toObject:(id)_anOBJ {
	/*
    if ( _aFunct == "grabCoordinates" ) {
 		gmNamespace.Event.addListener(_anOBJ, _anEvent, function(marker, point) { [drawLayer addDesignPoint:point]; });
    }
    else if ( _aFunct == "dragend" ) {
		gmNamespace.Event.addListener(_anOBJ, _anEvent, function() { [drawLayer modifyDesignPoint]; });
    }
    */
}



- (void) addEvent:(id)_anEvent aFunctionToCall:(CPString)_aFunct {
    if ( _aFunct == "grabCoordinates" ) {
             gmNamespace.Event.addListener(_gMap, _anEvent, function(marker, point) { [drawLayer addDesignPoint:point]; });
    }
}



- (MKMarker) addMarker:(MKMarker)aMarker atLocation:(MKLocation)aLocation {
    if (_mapReady) {
        var gMarker = [aMarker gMarker];
        gMarker.setLatLng([aLocation googleLatLng]);
        _gMap.addOverlay(gMarker);
    }
    else {
        // TODO some sort of queue?
    }
    return marker;
}



- (void) addMapItem:(MKMapItem)mapItem {
    [mapItem addToMapView:self];
}



- (MKLocation) center {
	if ( !_gMap ) {
		//alert("gMap not yet defined...");
		return _center;
	}
	var cent= _gMap.getCenter();
	var lngd= cent.lng();
	var lati= cent.lat();
	_center= [[MKLocation alloc] initWithLatitude:lati andLongitude:lngd]
    return _center;
}



- (void) createMap {
    var domWin = [self DOMWindow];
    _googleAjaxLoaded = YES;

	var loop= 0;
    do {
	    _DOMMapElement = domWin.document.getElementById('MKMapViewDiv');
    } while ( ! _DOMMapElement && loop++ < 10 );

    if ( ! _DOMMapElement )
    	return;

    if ( !gmNamespace )
        gmNamespace = google.maps;
	var gm = google.maps;
	var mapOptions = {
    	zoom: 4,
    	center:new gm.LatLng(9.93,-84.1)
    };

    _gMap= new gm.Map(_DOMMapElement, mapOptions);
    // _gMap.addMapType(G_SATELLITE_3D_MAP);
    // _gMap.setMapType(gm.G_PHYSICAL_MAP);
	// _gMap.setMapType(gm.MapTypeId.ROADMAP);
	// _gMap.mapTypeId(google.maps.MapTypeId.ROADMAP);
	// _gMap.setUIToDefault();
	// _gMap.enableContinuousZoom();

    _gMap.setCenter([_center googleLatLng], 6);
    _gMap.setZoom(_zoomLevel);

    _mapReady = YES;

	/*
    if (_loadingView)
        [_loadingView removeFromSuperview];

    if (delegate && [delegate respondsToSelector:@selector(mapViewIsReady:)])
        [delegate mapViewIsReady:self];
    */
}



- (JSObject) gMap {
    return _gMap;
}



- (JSObject) gmNamespace {
    var domWin = [self DOMWindow];
    if (domWin && _mapReady)
        return domWin.google.maps;
    return nil;
}



+ (JSObject) gmNamespace {
    return gmNamespace;
}



- (id) initWithFrame:(CGRect)aFrame apiKey:(CPString)apiKey {
    return [self initWithFrame:aFrame apiKey:apiKey center:nil];
}



- (id) initWithFrame:(CGRect)aFrame apiKey:(CPString)apiKey center:(MKLocation)aLocation {
    return [self initWithFrame:aFrame apiKey:apiKey center:aLocation loadingMarkup:nil];
}



- (id) initWithFrame:(CGRect)aFrame
             apiKey:(CPString)apiKey
             center:(MKLocation)aLocation
      loadingMarkup:(CPString)someLoadingMarkup {
    return [self initWithFrame:aFrame apiKey:apiKey center:aLocation loadingMarkup:someLoadingMarkup loadingView:nil];
}



- (id) initWithFrame:(CGRect)aFrame
             apiKey:(CPString)apiKey
             center:(MKLocation)aLocation
        loadingView:(CPString)aLoadingView
{
    return [self initWithFrame:aFrame apiKey:apiKey center:aLocation loadingMarkup:nil loadingView:aLoadingView];
}



- (id) initWithFrame:(CGRect)aFrame
             apiKey:(CPString)apiKey
             center:(MKLocation)aLocation
      loadingMarkup:(CPString)someLoadingMarkup
        loadingView:(CPString)aLoadingView
{
    _apiKey = apiKey;
    _center = aLocation;
    _someVari= -1;
    _zoomLevel = 14;

    if ( !_center ) {
        _center= [MKLocation locationWithLatitude:9.934 andLongitude:-84.0791];
		_zoomLevel= 4;
	}

    if (!someLoadingMarkup)
        someLoadingMarkup= @"";

    if ( self = [super initWithFrame:aFrame] ) {
        _scene = [[MKMapScene alloc] initWithMapView:self];
        _iframe.allowTransparency = true;

        var bounds = [self bounds];
        [self setFrameLoadDelegate:self];
        //&key=AIzaSyBEE0sW8iH_wO5DxIvBYsyqEs96UFS_oKc
        [self loadHTMLStringWithoutMessingUpScrollbars:@"<html><head></head><body style='padding:0px; margin:0px; background-color:transparent'><div id='MKMapViewDiv' style='left: 0px; top: 0px; width: 100%; height: 100%'>" + someLoadingMarkup + "</div></body><script type=\"text/javascript\" src=\"https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false\"></script></html>"];

        if (aLoadingView) {
            _loadingView = aLoadingView;
            [self addSubview:_loadingView];
        }
    }
    return self;
}



- (BOOL) isMapReady {
    return _mapReady;
}



- (void) loadGoogleMapsWhenReady {
    var domWin = [self DOMWindow];
    if (typeof(domWin.google) === 'undefined') {
        //domWin.window.setTimeout(function() {[self loadGoogleMapsWhenReady];}, 100);
        setTimeout(function() {[self loadGoogleMapsWhenReady];}, 100);
    }
    else {
        [self createMap];

        return;
 //       var googleScriptElement = domWin.document.createElement('script');
  //      domWin.mapsJsLoaded = function () {
  //          _googleAjaxLoaded = YES;
  //          _DOMMapElement = domWin.document.getElementById('MKMapViewDiv');
   //         alert("esta en la funcion");
  //          [self createMap];
  //      };
       // google.maps.event.addDomListener(window, 'load', initialize);
      //  googleScriptElement.innerHTML = "google.load('earth', '1');"
      // googleScriptElement.innerHTML = "google.maps.event.addDomListener(window, 'load', {'callback': mapsJsLoaded});"
    //   googleScriptElement.innerHTML = "google.maps.event.addDomListener(window, 'load', mapsJsLoaded);"
  //      domWin.document.getElementsByTagName('head')[0].appendChild(googleScriptElement);
    }
}



/* Overriding CPWebView's implementation */

- (void) _resizeWebFrame {
    var width = [self bounds].size.width,
        height = [self bounds].size.height;
    _iframe.setAttribute("width", width);
    _iframe.setAttribute("height", height);
    [_frameView setFrameSize:CGSizeMake(width, height)];
}



- (void) setFrameSize:(CGSize)aSize {
    [super setFrameSize:aSize];
}



- (void) setCenter:(MKLocation)aLocation {
    _center= aLocation;
    if ( _mapReady )
        _gMap.setCenter([_center googleLatLng]);
}



- (JSObject) setInMapWithLongitude:(float)lngd latitude:(float)lati draggable:(BOOL)drag icon:(CPString)iconURL title:(CPString)titl withShadow:(BOOL)shad {
    var gm= gmNamespace;
	var gMarkerOptions= { position:new gm.LatLng(lati,lngd), draggable:drag, icon:iconURL, title:titl, withShadow:shad };
	var gMarker= new gm.Marker(gMarkerOptions);
	gMarker.setMap(_gMap);
	//alert("gMarker="+gMarker+"   lngd="+lngd+"   lati="+lati+"   drag="+drag+"   icon="+iconURL+"   title="+titl);
	return gMarker;
}



- (JSObject) setInMapWithLongitudeForRMOptimization:(float)lngd latitude:(float)lati index:(CPString)inx draggable:(BOOL)drag icon:(CPString)iconURL title:(CPString)titl withShadow:(BOOL)shad {
    var gm= gmNamespace;
    // var gMarkerOptions= { position:new gm.LatLng(lati,lngd), draggable:drag, icon:iconURz, title:titl, withShadow:shad };
    var gMarkerOptions;
    if ( [inx intValue] >1 ) {
        gMarkerOptions= { position:new gm.LatLng(lati,lngd), draggable:drag, icon: {
        url: iconURL,
        scaledSize: new google.maps.Size(40, 40),
        origin:new google.maps.Point(-1, -7)
        },
        label: {
            
        color: 'black',
        fontSize:'15',
        fontWeight: 'bold',
        text: ""+[CPString stringWithFormat:@"%d",[inx intValue] - 1],
        },
            
            title:titl, withShadow:shad };
    }
    else {
        gMarkerOptions= { position:new gm.LatLng(lati,lngd), draggable:drag, icon: {
        url: iconURL,
        scaledSize: new google.maps.Size(40, 40),
        origin:new google.maps.Point(-1, -7)
        },
        label: {
            
        color: 'black',
        fontSize:'15',
        fontWeight: 'bold',
        text: ""+[CPString stringWithFormat:@" "],
        },
            
            title:titl, withShadow:shad };
    }
    
        
    var gMarker= new gm.Marker(gMarkerOptions);
    gMarker.setMap(_gMap);
    //alert("gMarker="+gMarker+"   lngd="+lngd+"   lati="+lati+"   drag="+drag+"   icon="+iconURL+"   title="+titl);
    
    
    return gMarker;
}



- (void) setZoom:(int)aZoomLevel {
    _zoomLevel = aZoomLevel;
    if ( _mapReady )
        _gMap.setZoom(_zoomLevel);
}



- (void) showcenter {
     alert(_gMap.getCenter());
 }



- (void) webView:(CPWebView)aWebView didFinishLoadForFrame:(id)aFrame {
    // this is called twice for some reason
    if (!hasLoaded)
        [self loadGoogleMapsWhenReady];
    hasLoaded = YES;
}



- (void) viewDidMoveToSuperview {
    if (!_mapReady && _googleAjaxLoaded)
        [self createMap];
    [super viewDidMoveToSuperview];
}



- (int) zoom {
    return _zoomLevel;
}

@end

