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

hq.labels = {
	
	nh : false,
	area : false,
	region : false,
	
	labels : {
	},

	layerIds : [],
	
	curTrans : null,
	
	lastZoom : false,
	
	$balloon : null,
	
	FadeInDt : 100,
	FadeOutDt : 500,

	BaseUrl : $j('#hqDomain').val(),
	
	init : function() {
		console.group( 'labels::init' );
		$j( '#contentWrapper' )
			.bind( 'paneLoaded', toolbox.delegate( this.onPaneLoaded, this ) )
			.bind( 'layerChange', toolbox.delegate (this.updateLabels, this))
			.bind( 'layerClear', toolbox.delegate ( this.clearLabels, this));	

		GEvent.addListener( hq.map.gMap, 'zoomend', toolbox.delegate( this.onZoom, this ) );
		GEvent.addListener( hq.map.gMap, 'dragend', toolbox.delegate( this.onZoom, this ) );
		GEvent.addListener( hq.map.gMap, 'moveend', toolbox.delegate( this.updateLabels, this ) );
	
		var zoom = hq.map.gMap.getZoom();
		this.lastZoom = zoom;
		$j( '#map' ).addClass( 'z' + zoom );
		
		this.onPaneLoaded();
		this.updateLabels();
	
		var layerIds = [];
		var overlays = $j('.overlay');
		var layerId = null;

		for(var i=0; i<overlays.length; i++) {
			layerId = $j(overlays[i]).attr('layerId')
			layerIds.push(layerId);
			this.labels[layerId] = {};
		}

		this.layerIds = layerIds;
		
		console.groupEnd();
	},
	
	onPaneLoaded : function() {
		console.group( 'labels::onPaneLoaded' );
		var $pane = $j( '#hq_idx_content' );
		this.market = $pane.attr( 'Market' );	
		this.nh = $j( '#hq_idx_content #nhId' ).val() || false;
		this.area = $j( '#hq_idx_content #areaId' ).val() || false;
		this.region = $j( '#hq_idx_content #regionId' ).val() || false;
		
		console.groupEnd();
	},

	onZoom : function( pre, post ) {
		console.group( 'labels::onZoom' );
		if( this.lastZoom ) {
			$j( '#map' ).removeClass( 'z' + this.lastZoom );
		}

		this.lastZoom = post;
		$j( '#map' ).addClass( 'z' + post );
		
		if( post < pre ) {
			
			console.info( "Zooming out" );
			
			this.nh = false;
			this.area = false;
			this.region = false;
			
//			this.updateLabels();
			
		}

	
		// Re-run listing search to only include listings within the current extents
		var spaceType = $j('#curSpaceType').val();
		if( spaceType==3 && false) {
			var bounds = hq.map.gMap.getBounds();
	                var ne = bounds.getNorthEast();
        	        var sw = bounds.getSouthWest();	
			var url = $j('#listUrl').val();

			url += '&maxX=' + ne.lng();
			url += '&minX=' + sw.lng();
			url += '&minY=' + sw.lat();
			url += '&maxY=' + ne.lat();
			url += '&byExtents=1';

			hq.ajax.loadLink(url);
		}

		console.groupEnd();
	},
	
	updateLabels : function(evt) {
		console.group( 'labels::updateLabels' );
		var layerChange = false;

		if( this.curTrans ) {
			console.info('Previous label load in progress, aborting');
			this.curTrans.abort();
			this.curTrans = null;
			hq.loadingMsg.hide();
		}

		if(evt && evt.type=='layerChange') {
			this.clearLabels();
			layerChange = true;
		}

		// If there are no tiles being drawn, no labels will appear
		if(evt && evt.noLayer) {
			this.clearLabels();

			console.groupEnd();

			return; 
		} else if($j('.activeLayer:first').hasClass('noLayer')) {
			this.clearLabels();

                        console.groupEnd();

                        return;
		} 
		
		else if($j('#cbId').val()) {
			this.clearLabels();
			console.groupEnd();
			return;
		}

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

		console.info(ne.lng()+','+sw.lng()+','+sw.lat()+','+ne.lat()+','+zoom);

		var layerId = (evt && !isNaN(evt.id)) ? evt.id : $j('a.activeLayer').attr('layerId');
		if(layerId=='areas')
			layerId=15;

		if(!layerId) {
			console.groupEnd();
			return;
		}
		
		var layerName = $j('a.activeLayer').attr('id');
		if(!layerName)
			layerName = '';

		hq.loadingMsg.show();

    this.curTrans = $j.getJSON('http://dev04.com/ws/labels.php?jsoncallback=?',
                {
			 minX : ne.lng(),
                                maxX : sw.lng(),
                                minY : sw.lat(),
                                maxY : ne.lat(),
                                nhId : this.nh,
                                areaId : this.area,
                                regionId : this.region,
                                marketId : this.market,
                                zoom : zoom,
                                altLayerId : layerId,
                                altLayerName : layerName
		}, toolbox.delegate( this.loadLabels, this ));

		console.groupEnd();

		return false;
	},
	
	loadLabels : function( res ) {
		console.group( 'labels::loadLabels' );
		len = res.length;
		var altLabel = false;
		var label = null;
		var level = null;

		if(len > 0)
			$j('#contentWrapper').trigger('onLabelsLoad');

		for(var j in this.labels) {
	                for(var k in this.labels[j]) {
        	                this.labels[j][k].hide();
                        }
                }

		var $pane = $j( '#hq_idx_content' );
                var mkt = $pane.attr( 'Market' );


		for( i=0; i<len; i++ ) {
			$type = res[i].type;

			level = 14;		
				
			if(this.labels[res[i].layerId][res[i].id]) {
				this.labels[res[i].layerId][res[i].id].show();
				continue;
			}

			var width = res[i].imgW ? res[i].imgW : 100;
			var height = res[i].imgH ? res[i].imgH : 100;

//			level = hq.map.gMap.getZoom(); 	
			label = new EInsert(new GLatLng(res[i].y, res[i].x), "http://wordpressidxplugin.com/wp-content/plugins/hq_idx/images/maplabels/"+mkt+"/"+$type+"/"+res[i].id+".png", new GSize(width, height), level, 5000, res[i].id );

			var data = {layerId: res[i].layerId, hqId: res[i].id};

			GEvent.addListener(label, 'click', toolbox.delegate(this.onLabel, this, data));


			if(label) {
				this.labels[res[i].layerId][res[i].id] = label;
		//		this.labels[res[i].layerId][res[i].id].show();		

				hq.map.gMap.addOverlay(label);

			}

		}
		
		hq.loadingMsg.hide();
		
		console.groupEnd();
	},

	//
	// NOTE: this will reset the Overlay menu. After completion, we need to reset the active layer to its previous value - toby	
	//
	onLabel : function( evt, data, labels, type ) {
		console.group( 'labels::onLabel' );
		if(data) {

		//var clickArg = type=='click' ? '&type=click' : '';
		var ssId = $j('#ssId').val();

		var url = $j('#pluginPath').val() + '/ajax.php?layerId=' + data.layerId + '&hqId=' + data.hqId;
                var bounds = hq.map.gMap.getBounds();
                var ne = bounds.getNorthEast();
                var sw = bounds.getSouthWest();


		if(ssId)  
			url +='&ssId=' + ssId + '&ssBypass=1';

		if( hq && hq.ajax ) {
			hq.ajax.loadLink( url );
		} else {
		//	$j( '#loadingMsg' ).fadeIn( this.FadeInDt );
			window.location = url;
		}
		
		}

		console.groupEnd();

		return false;
	},

	spaceReturn: function(res) {
	},
	
	onOverLabel : function( label, $link, suppressTip, who ) {
		clearTimeout(label.timeout);
		if(label.html.indexOf('_OVER.png')<0)
		{
			label.setContents(label.html.replace('.png','_OVER.png'));
		}
		if( $link )
			$link.find( '.spaceSummaryItem' ).addClass( 'hover' );
		label.timeout = setTimeout(toolbox.delegateNPA(who.onOutLabel,label,label,$link,1),1000);
	},
	
	onOutLabel : function( label, $link ) {
		label.setContents(label.html.replace('_OVER.png','.png'));		
		if( $link )
			$link.find( '.spaceSummaryItem' ).removeClass( 'hover' );
		
		//this.$balloon.hide();

	},

	clearLabels : function() {
		for(var j in this.labels) {
                        for(var k in this.labels[j]) {
                                this.labels[j][k].hide();
                        }
                }

	}
	
};

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