if( hq == undefined ) {
        var hq = {};
}

hq.map = {

        gMap : null,

        suspendSessionSave : null,

        init : function() {
                console.group( 'map::init' );

                if( GBrowserIsCompatible() == false ) {
                        throw new Error( "This browser is not compatible with Google Maps." );
                }

                this.gMap = new GMap2( $j( '#map' )[0] );
                var center = $j('#mapCenter').val();
                var zoom = parseInt($j('#mapZoom').val());
                center = center.split(',');

                // While the map does get recentered during the initial pane processing, removing this causes google maps to crash.
                this.gMap.setCenter( new GLatLng( center[0], center[1] ), zoom );

                this.gMap.addControl( new GLargeMapControl3D() );
             //   this.gMap.addControl( new GMapTypeControl() );
                this.gMap.addControl( new GScaleControl() );
                this.gMap.addControl( new GOverviewMapControl() );

                this.gMap.enableContinuousZoom();
                this.gMap.enableScrollWheelZoom();

                var $pane = $j( '#hq_idx_content' );

                this.mkt = $pane.attr( 'Market' );

                var activeLayer = $j('.activeLayer').attr('id');

                this.hideLoading = true;

                var mapType = $j('#hq_idx_content').attr('maptype');
                var mapTypeId = '';

                if(mapType) {
                        switch(mapType) {
                                case 'Satellite' :
                                    mapTypeId = 'satelliteView';

                                        break;
                                case 'Hybrid' :
                                        mapTypeId = 'hybridView';
                                        break;
                                case 'Physical' :
                                        mapTypeId = 'physicalView';
                                        break;
                                default :
                                        mapTypeId = 'mapView';
                        }

                        $j('#' + mapTypeId).trigger('click');

                       

                } else {
                        $j('#mapView').trigger('click');
                }


                // Change url to common shared variable - toby
                this.defaultLayer = new GTileLayer( null, 0, 18, {
                        tileUrlTemplate : 'http://wordpressidxplugin.com/g-tiles/'+this.mkt+'/' + activeLayer + '/{Z}/{X}/{Y}',
                        isPng : true,
                        opacity : .7
                });

                this.defaultOverlay = new GTileLayerOverlay( this.defaultLayer );
                this.overlay = this.defaultOverlay;

                this.gMap.addOverlay( this.defaultOverlay );

                this.clickCount = 0;

                //this.mmgrOptions = { borderPadding: 50, maxZoom: 17, trackMarkers: false };
                //this.mmgr = new MarkerManager(this.gMap,this.mmgrOptions);
                var m = this;
                $j( '#mapWrapper' ).addClass( 'hq_idx_evtBound' ).resize( toolbox.delegate( this.resize, this ) )
                .click(function() {
                        m.clickCount++;
                });
                $j( '#contentWrapper' )
                        .bind( 'postPaneLoad', toolbox.delegate( this.onPostPaneLoad, this ) )
                        .bind( 'layerChange', toolbox.delegate( this.addLayer, this ) )
                        .bind( 'layerChange', toolbox.delegate( this.saveSessionVars, this ) );

                // Save extents in the session on move end
                this.sessionListener = GEvent.addListener( hq.map.gMap, 'moveend', toolbox.delegate( this.saveSessionVars, this ) );

                //$j('.overlay').click(toolbox.delegate(this.saveSessionVars, this));

                $j( window ).unload( toolbox.delegate( this.unload, this ) );

                this.onPostPaneLoad();


		 // Turn on walk score if specified
                var ws = $j('#showWalkScore').val();
                if(ws && ws!=0) {
                        if($j('#WalkScore').length) {
                                $j('#WalkScore').trigger('click');
                        }
                }

                console.groupEnd();
        },

        resize : function() {
                console.group( 'map::resize' );

                this.gMap.checkResize();
                this.onPostPaneLoad();
                console.groupEnd();
        },

        unload : function() {
                console.group( 'map::unload' );

                GUnload();

                console.groupEnd();
        },

        onPostPaneLoad : function( evt ) {
                console.group( 'map::onPostPaneLoad' );

                var $pane = $j( '#hq_idx_content' );
                var yMin = $pane.attr( 'yMin' );
                var yMax = $pane.attr( 'yMax' );
                var xMin = $pane.attr( 'xMin' );
                var xMax = $pane.attr( 'xMax' );
                var $spaceType = $j('#curSpaceType').val();
                var doZoom = $j('#doZoom').val();
                var loadedSpaces = $j('#loadedSpaceIds').val();

                if(loadedSpaces)
                        loadedSpaces = loadedSpaces.split(',');

                if(this.clickCount < 2  && (!loadedSpaces || loadedSpaces.length==1)) {
                        doZoom = true;
                        $j('#doZoom').val('');
                }

                if( yMin && yMax && xMin && xMax )
                {
                        var bounds = new GLatLngBounds();
                        bounds.extend( new GLatLng( yMin, xMin, true ) );
                        bounds.extend( new GLatLng( yMax, xMax, true ) );

                        if(($spaceType!=4 && $spaceType!=3 && $spaceType!='') || doZoom) {
                        hq.map.gMap.setCenter( bounds.getCenter() );

                        if(doZoom)
                                 hq.map.gMap.setZoom(  hq.map.gMap.getBoundsZoomLevel( bounds ) );
                        }
                }

                if(this.hideLoading) {
                        this.hideLoading = false;
                }

		// Set the correct map overlay selection(s)
		if(this.overlayElem)
			$j('#' + this.overlayElem).parents('table:first').find('img:first').show();
		if(this.mapTypeElem)
			$j('#' + this.mapTypeElem).parents('table:first').find('img:first').show();

                $j('#idx_wrapper .nsOverlay').click(toolbox.delegate(this.onNSOverlay, this));

		this.saveSessionVars(evt);

                console.groupEnd();
        },

        getBounds : function() {
                console.group( 'map::getBounds' );

                var bounds = hq.map.gMap.getBounds();
                var ne = bounds.getNorthEast();
                var sw = bounds.getSouthWest();

                //console.info(ne.lng()+','+sw.lng()+','+sw.lat()+','+ne.lat());
                var res = {
                        minX : ne.lng(),
                        maxX : sw.lng(),
                        minY : sw.lat(),
                        maxY : ne.lat()
                };

                console.groupEnd();

                return res;
        },


        // Non searchable overlay was clicked
        onNSOverlay : function(evt) {
            console.group('map::onNSOverlay');

            var $tgt = $j(evt.target);
            var id = $tgt.attr('id');
            var url = $tgt.attr('layerLocation');
            var active = $tgt.hasClass('active');

	    // Overlays using a url, such as walkscore
            if(url) {
                if(this.nsOverlay) {
                	this.gMap.removeOverlay(this.nsOverlay);
                        $tgt.parents('table:first').find('img:first').hide();
			this.nsOverlay = null;
                } else {

                 this.nsLayer = new GTileLayer( null, 0, 18, {
        	                tileUrlTemplate : url,
                	        isPng : true,
	                       	opacity : .7
        		});

                 this.nsOverlay = new GTileLayerOverlay(this.nsLayer);
                 this.gMap.addOverlay( this.nsOverlay);

                 var elem = $tgt.parents('table:first').find('img:first');
		 elem.show();

		 this.overlayElem = id;
             }


	    // Google map types
            } else if ($tgt.hasClass('googleOverlay')) {
                $j('.mapTypeCheck').hide();

                var mapConst = null;
                switch(id) {
				case 'satelliteView' :
					mapConst = G_SATELLITE_MAP;
					break;
				case 'hybridView' :
					mapConst = G_HYBRID_MAP;
					break;
                                case 'physicalView' :
					mapConst = G_PHYSICAL_MAP;
					break;
				default :
					mapConst = G_NORMAL_MAP;
			}

                this.gMap.setMapType(mapConst);

                var elem = $tgt.parents('table:first').find('img:first');
		elem.show();

		this.mapTypeElem = id;
            }

            console.groupEnd();

            return false;
        },
        
        addLayer : function(evt) {
                console.group('map::addLayer');

//              $j( '#loadingMsg' ).fadeIn( this.FadeInDt );

                // Reset click count for zooming after layer change
                this.clickCount = 0;

                if(this.overlay)
                        this.gMap.removeOverlay(this.overlay);
                if(evt.noLayer==false) {
			
                        var mlayer = evt.id;
                        var url = evt.layerLocation;

                        if(!mlayer || mlayer==undefined || mlayer==101) {
                                console.groupEnd();

                                return false;
                        }

                        if(!url)
                                url = 'http://wordpressidxplugin.com/g-tiles/'+this.mkt+'/' + mlayer + '/{Z}/{X}/{Y}';


                        this.layer = new GTileLayer( null, 0, 18, {
                                tileUrlTemplate : url,
                                isPng : true,
                                opacity : .7
                        });

                        this.overlay = new GTileLayerOverlay( this.layer, {zPriority: 1000} );

                        this.gMap.addOverlay( this.overlay );

                        if(!evt.noClear)
                                hq.ajax.loadLink($j('#pluginPath').val() + '/ajax.php?layerOp=clearLoaded');

                }


//              $j( '#loadingMsg' ).fadeOut( this.FadeOutDt );

                console.groupEnd();
        },

        // Save the current extents, activeLayer etc  in the session, so we can use them on page reloads
        saveSessionVars : function(evt) {
                console.group('map::saveSessionVars');

                if((evt && evt.noSessionSave) || this.suspendSessionSave) {
                    console.groupEnd();
                    return;

                }


                if(this.sessionTrans) {
                        console.info('Current session save in progress. Aborting...');
                        this.sessionTrans.abort();
                        this.sessionTrans = null;
                }

                if(evt) {
                        var $tgt = $j(evt.target);
                        var activeLayerId = $tgt.attr('layerId');
                } else {
                        var activeLayerId = $j('.activeLayer').attr('layerId');

                }

                var zoom = hq.map.gMap.getZoom();
                var bounds = hq.map.gMap.getBounds();
                var ne = bounds.getNorthEast();
                var sw = bounds.getSouthWest();

                minX = ne.lng(),
                maxX = sw.lng(),
                minY = sw.lat(),
                maxY = ne.lat()

                this.sessionTrans = $j.ajax({
                        data : {
                                op : 'saveSessionVars',
                                minX : minX,
                                minY : minY,
                                maxX : maxX,
                                maxY : maxY,
                                activeLayerId : activeLayerId
                        },
                        url : $j('#pluginPath').val()  + '/utilities/session-save.php'
                });

                console.groupEnd();

                return false;
        },

        stopSessionSave : function() {
            this.suspendSessionSave = true;
            GEvent.removeListener(this.sessionListener);
        },

        startSessionSave : function() {
             this.suspendSessionSave = false;
             this.sessionListener = GEvent.addListener( hq.map.gMap, 'moveend', toolbox.delegate( this.saveSessionVars, this ) );
        }


};

$j( document ).ready( toolbox.delegate( hq.map.init, hq.map ) );
