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

hq.listings = {
	
	markers : [],
	baseIcon : null,
	path : "/wp-content/plugins/hq_idx/images/icon_pack/listing-",
	
	$balloon : null,
	
	init : function() {
		console.group( 'Listings::init' );
		
		this.baseIcon = new GIcon( G_DEFAULT_ICON, this.path + 'blue.png' );
		this.baseIcon.iconSize = new GSize( 24, 24 );
		this.baseIcon.iconAnchor = new GPoint( 12, 12);
		this.baseIcon.imageMap = [0,0, 23,0, 23,23, 0, 23];
		//this.baseIcon.imageMap = [7, 2, 16, 2, 21, 7, 21, 15, 12, 36, 11, 36, 2, 15, 2, 7, 7, 2];
		this.baseIcon.shadow = '';//this.path + 'shadow.png';
		this.baseIcon.shadowSize = new GSize( 0, 0 );
		//this.baseIcon.transparent = this.path + 'trans.png';
		
		//this.mmgrOptions = { borderPadding: 50, maxZoom: 17, trackMarkers: false };
		//this.mmgr1 = new MarkerManager(hq.map.gMap,this.mmgrOptions);
		
		
		$j( '#contentWrapper' ).bind( 'paneLoaded', toolbox.delegate( this.onPaneLoaded, this ) );
		$j( '#contentWrapper' ).bind( 'prePaneLoad', toolbox.delegate( this.onPrePaneLoad, this ) );
		this.onPaneLoaded();
	
		this.$balloon = $j( "<div id='listingBalloon'></div>" ).hide().appendTo( $j( '#mapWrapper' ) );
		
		console.groupEnd();
	},
	
	onPaneLoaded : function() {
		console.group( 'Listings::onPaneLoaded' );
		
		var pageId = $j( 'body' ).attr( 'id' );
		
		// Clear all old markers
		//this.mmgr1.clearMarkers();
		for( var i=0; i<this.markers.length; i++ ) {
			hq.map.gMap.removeOverlay( this.markers[i] );
		}
		this.markers = [];
			
		// Prev/Next listing detail photos
		if( $j( '#listingDetail #photoNavBox' ).length ) {
			$j( '#listingDetail #prevPhoto' ).unbind().click( toolbox.delegate( this.onPrevPhoto, this ) );
			$j( '#listingDetail #nextPhoto' ).unbind().click( toolbox.delegate( this.onNextPhoto, this ) );
			$j( '#listingDetail #photoBox' ).addClass( 'evtBound' ).click( toolbox.delegate( this.onNextPhoto, this ) );
		}

		$j( '.selectAllBtn' ).click( toolbox.delegate( this.onSelectAll, this ) );
		$j( '.selectNoneBtn' ).click( toolbox.delegate( this.onSelectNone, this ) );
		
		$j( '#updateOrderBtn' ).hide( );
		$j( '#selectOrderBy' ).change( function( ) { $j( '#updateOrderBtn' ).click( ); } );
		
		var $links = $j( '#contentWrapper a.listingItem[lat][lng]' );
		
		var activeMarker = null;
		
		var len = $links.length
		for( var i=0; i<$links.length; i++ ) {
			
			var $link = $j( $links[i] );
			var lng = $link.attr( 'lng' );
			var lat = $link.attr( 'lat' );
			var color = ( $link.attr( 'type' ) === 'changed' ? 'green' : 'blue' );
			var active = ( $link.attr( 'active' ) === 'true' ? '-active' : '' );
			var marker = new PdMarker( new GLatLng( lat, lng ), {
				icon : new GIcon( this.baseIcon, this.path + color + active + ".png" )
			});
			
			marker.hqColor = color;
			marker.hqActive = !!active;
			if(marker.hqActive)
				activeMarker = marker;
			
			$link.addClass( 'evtBound' )
				.mouseover( toolbox.delegate( this.onMouseOver, this, $link, marker ) )
				.mouseout( toolbox.delegate( this.onMouseOut, this, $link, marker ) );
				
			
			GEvent.addListener( marker, 'click', toolbox.delegate(this.onClick, this, $link, marker) );
			GEvent.addListener( marker, 'mouseover', toolbox.delegate( this.onMouseOver, this, $link, marker ) );
			GEvent.addListener( marker, 'mouseout', toolbox.delegate( this.onMouseOut, this, $link, marker ) );

			this.markers[ this.markers.length ] = marker;
			hq.map.gMap.addOverlay( marker );
			
		}
		//this.mmgr1.addMarkers(this.markers,7,17);
		//this.mmgr1.refresh();
		
		if(activeMarker != null) {
			activeMarker.topMarkerZIndex();
		}		
		// Filters
		$j( '#filters #filterBtn' ).click( toolbox.delegate( this.toggleFilters, this ) );
		
		console.groupEnd();
	},
	
	onClick : function(evt, $link, marker) {
		marker.setImage( this.path + marker.hqColor + "-active.png" );
		marker.topMarkerZIndex(); 
		
		var href = $link.attr('href');
		if(hq && hq.ajax) 
			hq.ajax.loadLink( href );
		else 
			window.location = href;
	},
	
	onPrePaneLoad : function() {
		this.$balloon.hide();
	},
	
	
	toggleFilters : function() {
		console.group( 'Listings::toggleFilters' );
		
		var $filters = $j( '#filters' );
		
		if( $filters.hasClass( 'open' ) ) {
			$filters.removeClass( 'open' ).addClass( 'closed' );
		} else {
			$filters.removeClass( 'closed' ).addClass( 'open' );
		}
		
		console.groupEnd();
	},
	
	hideFilters : function() {
		console.group( 'Listings::hideFilters' );
		
		$j( '#filtersForm' ).hide();
		$j( '#filterSummary').show();
		
		console.groupEnd();
		return false;
	},
	
	onPrevPhoto : function() {
		console.group( 'Listings::onPrevPhoto' );
		
		var $elem = $j( '#currentPhoto');
		if( $elem.length == 0 ) {
			throw new Error( 'Failed to locate current photo element' );
		}
		var cur = parseInt( $elem.attr( 'cur' ) );
		var len = parseInt( $elem.attr( 'len' ) );
		
		var nxt;
		
		if( len == 1 ) {
			nxt = 0;
		} else if( cur == 0 ) {
			nxt = len - 1;
		} else {
			nxt = cur - 1;
		}
		
		if( cur != nxt ) {
			$j( '#photoBox img[n=' + nxt + ']' ).css( 'display', 'block' );
			$j( '#photoBox img[n=' + cur + ']' ).css( 'display', 'none' );
		}
		
		$elem.attr( 'cur', nxt );
		$elem.html( ( nxt + 1 ) + ' of ' + len );
		
		console.groupEnd();
		return false;
	}, 
	
	onNextPhoto : function() {
		console.group( 'Listings::onNextPhoto' );
		
		var $elem = $j( '#currentPhoto');
		if( $elem.length == 0 ) {
			throw new Error( 'Failed to locate current photo element' );
		}
		var cur = parseInt( $elem.attr( 'cur' ) );
		var len = parseInt( $elem.attr( 'len' ) );
		
		var nxt;
		
		if( len == 1 ) {
			nxt = 0
		} else if( cur == len - 1 ) {
			nxt = 0;
		} else {
			nxt = cur + 1;
		}
		
		if( nxt != cur ) {
			$j( '#photoBox img[n=' + nxt + ']' ).css( 'display', 'block' );
			$j( '#photoBox img[n=' + cur + ']' ).css( 'display', 'none' );
		}
		
		$elem.attr( 'cur', nxt );
		$elem.html( ( nxt + 1 ) + ' of ' + len );
		
		console.groupEnd();
		return false;
	},
	
	onMouseOver : function( evt, $link, marker) {
		
		$link.addClass( 'hover' );
		var active = ( marker.hqActive ? "-active" : "" );
		marker.setImage( this.path + marker.hqColor + active + "-active.png" );
		marker.topMarkerZIndex(); 
		
		var iconHeight = marker.getIcon().iconSize.height;
		var windowWidth = $j( '#mapWrapper' ).width();
		
		var latLng = marker.getLatLng();
		var px = hq.map.gMap.fromLatLngToContainerPixel( latLng );
				
		
		var top = px.y - this.$balloon.height() - parseInt(iconHeight/2);
		var v = 'u';
		
		if( top < 0 ) {
			top = px.y +2;
			v = 'l';
		}
		
		var left = px.x - 30;
		var h = 'r';
		
		if( left + this.$balloon.width() > windowWidth ) {
			left = px.x - 252;
			h = 'l';
		}
		
		
		var url = "url(/wp-content/plugins/hq_idx/images/lb-" + v + h + ".png)";
		var className = v + h + "Balloon";
		
		this.$balloon.css({
			top : top + 'px',
			left : left + 'px',
			backgroundImage : url
		});
		
		this.$balloon.html( $link.attr( 'tooltip' ) );
		this.$balloon[0].className = className;
		this.$balloon.show();
		
	}, 
	
	
	onMouseOut : function( evt, $link, marker ) {
		
		$link.removeClass( 'hover' );
		var active = ( marker.hqActive ? "-active" : "" );
		marker.setImage( this.path + marker.hqColor + active + ".png" );
		marker.restoreMarkerZIndex();

		this.$balloon.hide();
		
	},
	
	updateZIndex : function( marker) {
		console.group( 'listings::updateZIndex' );
		var res = GOverlay.getZIndex( marker.getPoint().lat() );
		console.groupEnd();
		return res;
	},
	
	onSelectAll : function ( evt ) {
		var $tgt = $j(evt.target);
		var selectClass = $tgt.attr('selectClass');
		
		if( selectClass ) {
			$j('.' + selectClass).attr('checked', true);
		}
	},
	
	onSelectNone : function( evt ) {
		var $tgt = $j(evt.target);
		var selectClass = $tgt.attr('selectClass');
		
		if( selectClass ) {
			$j('.' + selectClass).attr('checked', false);
		}
	}
	
};

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