@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 MKMapView : CPWebView  { // CPWebView
    CPString        _apiKey;
    DOMElement      _DOMMapElement;
     //JSObject        _gMap               @accessors(property=gMap);
    id              _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);

    id              _essDele;

    CPString        mapId               @accessors;
    id              searBoxx;        // caja para busquedas
}



- (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];/* We must modify the position of the respective point of that marker */ });
    }
}



- (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];
}

-(void) setESSDele:(id)_ess{
    _essDele = _ess;
}

- (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 {

   // console.log("Create Map ");
    var domWin = [self DOMWindow];
    _googleAjaxLoaded = YES;

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

   // console.log("_DOMMapElement ");

    if ( ! _DOMMapElement )
    	return;

    if ( !gmNamespace )
        gmNamespace = google.maps;
	var gm = google.maps;
	var mapOptions = {
        streetViewControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
    	zoom: 10,
    	center:new gm.LatLng(9.93,-84.1)
    };

    var newId = [[CPString UUID] substringToIndex:10];
    
//var map;
            $( document ).ready(function() {

                mapId = 'rm_map_id'+ newId;
                self._DOMElement.className = "rm_map"+ newId;

                $(".rm_map"+ newId).attr('id', mapId);

                
                function initMap() {
                _gMap = new google.maps.Map(document.getElementById(mapId), {
                    center: {lat: 9.93, lng: -84.1},
                    zoom: 10,
                    draggable: true,
                    mapTypeControl: true,
                    mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                    mapTypeIds: ['roadmap','terrain','satellite','hybrid']}
                    });
                }

                initMap();

                try {
                    var barraTitulo = $("#"+mapId).parent().parent().children().eq(1);
                    barraTitulo.css("background-color", "black");
                    barraTitulo.css("color", "white");
                    barraTitulo.css("margin-left", "-27px");
                    barraTitulo.css("width", "100%");

                     barraTitulo.children().eq(1).children().eq(0).css("display", "none");
                }
                catch(err) {
                    console.log("Cant format the map title bar");
                }
                

                $("#"+mapId).parent().append("<input id='pac-input' class='controls' type='text' placeholder='Search Box'><div id='currMap'></div><script>");
                searBoxx = $("#"+mapId).parent().children().eq(1);
                searBoxx.css("z-index","1");
                searBoxx.css("display","none");


        });

   // _gMap= new gm.Map(_DOMMapElement, mapOptions);

  //   console.log("se creo el mapa ");
    // _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];
    */

    [_essDele windowMapSetupEnd];
}



/*
- (JSObject) gMap {
    return _gMap;
}
*/
- (id) 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 {
    //console.log("Metodo 1");
    return [self initWithFrame:aFrame apiKey:apiKey center:nil];
}



- (id) initWithFrame:(CGRect)aFrame apiKey:(CPString)apiKey center:(MKLocation)aLocation {
   // console.log("Metodo 2");
    return [self initWithFrame:aFrame apiKey:apiKey center:aLocation loadingMarkup:nil];
}



- (id) initWithFrame:(CGRect)aFrame
             apiKey:(CPString)apiKey
             center:(MKLocation)aLocation
      loadingMarkup:(CPString)someLoadingMarkup {
     //   console.log("Metodo 3");
    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
{  // console.log("Metodo 4");
    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
{  // console.log("Metodo 5");

    _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] ) {
        [self setDelegate:self];
        _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&key=AIzaSyCRoA5SknDayXD8Rs44vui4TQSdqhfVTF0\"></script><style type = 'text/css'> .labels {color: blue; text-shadow: 2px 0 0 #fff, -2px 0 0 #fff, 0 2px 0 #fff, 0 -2px 0 #fff, 1px 1px #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff; font-family: 'Arial', 'Arial', sans-serif; font-size: 11px; font-weight: 900;text-align: center;} </style></html>"];
        [self setScrollMode:CPWebViewScrollAuto];
        if (aLoadingView) {
            _loadingView = aLoadingView;
            [self addSubview:_loadingView];
        }
    }
    return self;
}



- (BOOL) isMapReady {
    return _mapReady;
}



- (void) loadGoogleMapsWhenReady {
   // console.log("load google when is ready");
    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 */
- (BOOL) _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;
}



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



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



- (void) webView:(CPWebView)aWebView didFinishLoadForFrame:(id)aFrame {

   // console.log("didFinishLoadForFrame");
    // 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

