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

hq.listings = {
	
	markers : {},
	baseIcon : null,
	path : null,
	
	$balloon : null,
	
	init : function() {
		console.group( 'Listings::init' );

		this.path = $j('#pluginPath').val() + '/images/icon_pack/listing-';
		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 ) )
			.bind( 'prePaneLoad', toolbox.delegate( this.onPrePaneLoad, this ) )
			.bind( 'layerChange', toolbox.delegate(	this.clear, this ) );

                GEvent.addListener(hq.map.gMap, 'moveend', toolbox.delegate(this.resizeIcons, this));
                             
		this.onPaneLoaded();
	
		this.$balloon = $j( "<div id='listingBalloon'></div>" ).hide().appendTo( $j( '#mapWrapper' ) );
		
		console.groupEnd();
	},
	
	onPaneLoaded : function() {
		console.group( 'Listings::onPaneLoaded' );
		
	//	$j( '#loadingMsg' ).fadeIn( this.FadeInDt );

		var z = hq.map.gMap.getZoom();
                 var marker = null;
                        var icon = null;
                        this.size = {
                                height: 24,
                                width: 24};


                 var scale = Math.pow(1.4,(z - 12));
                                if(scale > 1)
                                        scale = 1;

                                var h=this.size.height * scale;
                                var w=this.size.width * scale;

		
		for(var i in this.markers) {
			this.markers[i].hide();
		}
				
		// 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 ) );
		
		// Hide Order by submit btn
		$j( '#updateOrderBtn' ).hide( );
		$j( '#selectOrderBy' ).change( function( ) { $j( '#updateOrderBtn' ).click( ); } );
		
		// Hide Orange dot filter submit btn
		$j( '#viewCountSubmit' ).hide( );
		$j( '#viewCountSelect' ).change( function( ) { $j( '#viewCountSubmit' ).click( ); } );

		if(!$j('#loadedSpaceIds').val() && !$j('#byExtents').val()) {
	               	$j('.filtersForm').find('input').css('background-color', '#DFDFDF').attr('disabled', 'disabled');
        	        $j('.filtersForm').find('select').css('background-color', '#DFDFDF').attr('disabled', 'disabled');
		}
		
		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 listingId = $link.attr('listingId');
			var lng = $link.attr( 'lng' );
			var lat = $link.attr( 'lat' );
			var viewed = $link.attr('viewed');
			var color = ( $link.attr( 'type' ) === 'changed' ? 'green' : 'blue' );
			if(viewed) color = 'orange';
			var opts = null;
			var active = ( $link.attr( 'active' ) == 'true' ? '-active' : '' );
			
			if(!this.markers[listingId]) {

				icon = new GIcon();
				icon.iconSize = new GSize(h,w);
				icon.shadowSize = new GSize(0,0);
				icon.iconAnchor = new GPoint(12, 12);
				
				icon.image = this.path + color + active + ".png"; // + "?listingId=" + listingId;

				opts = {
					icon: icon,
					clickable: true
				};

//				marker = new hq.map.gMap.createZMarker(new GLatLng(lat, lng), opts);
				marker = new GMarker(new GLatLng(lat, lng), icon, false);
			
				hq.map.gMap.addOverlay(marker);
				this.markers[listingId] = marker;
				this.markers[listingId].show();
				this.markers[listingId].listingId = listingId;
	
//				this.markers[listingId].setImage(this.path + color + active + ".png");

				GEvent.addListener(this.markers[listingId], 'click', toolbox.delegate(this.onClick, this, $link, this.markers[listingId]));
				GEvent.addListener(this.markers[listingId], 'mouseover', toolbox.delegate(this.onMouseOver, this, $link, this.markers[listingId]));
				GEvent.addListener(this.markers[listingId], 'mouseout', toolbox.delegate(this.onMouseOut, this, $link, this.markers[listingId]));


			} else {
				this.markers[listingId].show();
				this.markers[listingId].setImage(this.path + color + active + ".png");

//				continue;
			
			}

			this.markers[listingId].hqColor = color;
			this.markers[listingId].hqActive = !!active;
			if(this.markers[listingId].hqActive)
				activeMarker = this.markers[listingId];

	
		
			$link.addClass( 'evtBound' )
				.mouseover( toolbox.delegate( this.onMouseOver, this, $link, this.markers[listingId] ) )
				.mouseout( toolbox.delegate( this.onMouseOut, this, $link, this.markers[listingId] ) );
			
	
			
		}

		// resize the icons in case they had already been created and had been previously scaled
		this.resizeIcons();
	
//		if(activeMarker != null) {
			//activeMarker.topMarkerZIndex();
//		}		
		// Filters
		$j( '.filters .filterBtn' ).click( toolbox.delegate( this.toggleFilters, this ) );
	
	//	$j( '#loadingMsg' ).fadeOut( this.FadeOutDt );
			

		console.groupEnd();
	},
	
	onClick : function(evt, $link, marker) {
		var $target = $j( evt.target );
		marker.setImage( this.path + marker.hqColor + "-active.png" );
		marker.hqActive = "-active";

		
		//marker.topMarkerZIndex(); 
		var ssId = $j('#ssId').val();
		var href = $link.attr('href');
		
		if(ssId)
                        href +='&ssId=' + ssId + '&ssBypass=1';

		if(hq && hq.ajax) 
			hq.ajax.loadLink( href );
		else 
			window.location = href;

		return false;
		
	},
	resizeIcons : function() {	
		var z = hq.map.gMap.getZoom();
                var marker = null;
                        var icon = null;
		var spaceType = $j('#loadedSpaceType').val();
		var level = spaceType==4 ? 14 : 12;

                 var scale = Math.pow(1.4,(z - level));
                                if(scale > 1)
                                        scale = 1;

                var h=24 * scale;
                var w=24 * scale;
		 var test = $j('#map div').find('img[src*="listing-"]');
                $j('#map div').find('img[src*="listing-"]').width(w).height(h);

	},
	
	onPrePaneLoad : function() {
		this.$balloon.hide();

	},
	
	
	toggleFilters : function(evt) {
		console.group( 'Listings::toggleFilters' );
		var $tgt = $j(evt.target);
		var $div = $tgt.parents('.filters');
		if( $div.hasClass( 'open' ) ) {
			$div.removeClass( 'open' ).addClass( 'closed' );
			$j('#filtersArrow').attr('src', $j('#pluginPath').val() + '/images/drop-down-menu-closed.gif');
		} else {
			$div.removeClass( 'closed' ).addClass( 'open' );
			$j('#filtersArrow').attr('src', $j('#pluginPath').val() + '/images/drop-down-menu-open.gif');
		}
			
		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) {
		var listingId = marker.listingId;
		var elem = $j("img[src*='listingId=" + listingId + "']");

		$j(elem).css('z-index', 10000);

		$link.addClass( 'hover' );
		var viewDate = false; //$link.attr('viewed');
		var active = ( marker.hqActive ? "-active" : "" );

//		$j(marker.div_).find('img').attr('src', this.path + marker.hqColor + active + "-active.png");

		marker.setImage( this.path + marker.hqColor + active + "-active.png?" + 'listingId=' + listingId );
		
		//marker.topMarkerZIndex(); 
		var iconHeight = 24;// marker.getIcon().iconSize.height;
		var windowWidth = $j( '#mapWrapper' ).width();
		
		var latLng = marker.getPoint();
		var px =  hq.map.gMap.fromLatLngToContainerPixel( latLng );
				
		
		var top = px.y - this.$balloon.height() - parseInt(iconHeight/2) + 2;
		var v = 'u';
		
		if( top < 0 ) {
			top = px.y+15;
			v = 'l';
		}
		
		var width = 0;
		if(viewDate) {
			width = 380;
		} else {
			width = 280;
		}
		
		var left = px.x - 30;
		var h = 'r';
		
		if( left + width > windowWidth ) {
			h = 'l';
		}
		
		var url = '';
		
		if(viewDate) {
			url = "url(" + $j('#pluginPath').val() + "/images/balloon_orange_" + v + h + ".png)";
		}
		else {
			url = "url(" + $j('#pluginPath').val() + "/images/lb-" + v + h + ".png)";
		}
		
		if(left + width > windowWidth) {
		if(viewDate) 
				left = px.x - 342;
			else 
				left = px.x - 242;
		}
			
		var className = v + h + "Balloon";
		
		this.$balloon.css({
			top : top + 'px',
			left : left + 'px',
			backgroundImage : url,
			width : width
		});
		
		this.$balloon.html( $link.attr( 'tooltip' ) );
		this.$balloon[0].className = className;
		this.$balloon.show();

		
	}, 
	
	
	onMouseOut : function( evt, $link, marker ) {
		var listingId = marker.listingId;
                var elem = $j("img[src*='listingId=" + listingId + "']");
		$j(elem).css('z-index', 0);
		$link.removeClass( 'hover' );
		var active = ( marker.hqActive ? "-active" : "" );
		marker.setImage( this.path + marker.hqColor + active + ".png?listingId=" + listingId );
		//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);
		}
	},
	clear : function(evt) {
		console.group('lisitngs::clear');
		for(var i in this.markers) {
                        this.markers[i].hide();
                }
		console.groupEnd();
	}
	
};

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