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.setZoom(parseInt(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 mapConst = null;
		if(mapType) {
			switch(mapType) {
				case 'Satellite' :
					mapConst = G_SATELLITE_MAP;
					break;
				case 'Hybrid' :
					mapConst = G_HYBRID_MAP;
					break;
				default :
					mapConst = G_NORMAL_MAP;
			}

			hq.map.gMap.setMapType( mapConst )

		}

		
		// 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( '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();
		
		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 ) );
			else 
				 hq.map.gMap.setZoom( 10 );
			}
		}

		if(this.hideLoading) {
			this.hideLoading = false;
//			hq.loadingMsg.hide();
		}
		

		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;
	},
	
	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 );
		
			this.gMap.addOverlay( this.overlay );
				
			if(!evt.noClear)
				hq.ajax.loadLink($j('#pluginPath').val() + '/searchlistings.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 ) );
