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

hq.wpPosts = {
	
	markers : [],
	baseIcon : null,
	path : null,
	imgBase : null,
	
	$balloon : null,
	
	init : function() {
		console.group( 'WpPosts::init' );

		this.path = 'http://pluginimages.s3.amazonaws.com' + '/icon_pack/';		
		this.imgBase = 'http://pluginimages.s3.amazonaws.com';

		this.baseIcon = new GIcon( G_DEFAULT_ICON, this.path + '.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.markers = {};

		//this.baseIcon.transparent = this.path + 'trans.png';
		//this.mmgrOptions = { borderPadding: 50, maxZoom: 17, trackMarkers: false };
		//this.mmgr2 = new MarkerManager(hq.map.gMap,this.mmgrOptions);
		$j( '#contentWrapper' )
			.bind( 'paneLoaded', toolbox.delegate( this.onPaneLoaded, this ) )
			.bind( 'layerChange', toolbox.delegate( this.clear, this ) );

		
		GEvent.addListener(hq.map.gMap, 'moveend', toolbox.delegate(this.resizeIcons, this));
		
		this.onPaneLoaded();
		
		this.$balloon = $j('#listingBalloon');
		
		console.groupEnd();
	},


	clear : function() {
		for(var i in this.markers) {
                        this.markers[i].hide();
                }

	},

	
	onPaneLoaded : function() {
		console.group( 'WpPosts:onPaneLoaded' );
	
		  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;

                //$j('#map div').find('img[src$="listing-blue.png"]').width(w).height(h);
                //$j('#map div').find('img[src$="listing-blue-active.png"]').width(w).height(h);
                //$j('#map div').find('img[src$="listing-green.png"]').width(w).height(h);
                //$j('#map div').find('img[src$="listing-green-active.png"]').width(w).height(h);

                var pageId = $j( 'body' ).attr( 'id' );

		this.clear();

                var $links = $j( '#contentWrapper a.wpPostLink[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 postId = $link.attr('postId');
		
			if( lng && lat ) {
				var color = '';//( $link.attr( 'type' ) === 'changed' ? 'green' : 'blue' );
				var active = ( $link.attr( 'active' ) === 'true' ? '-active' : '' );
				var cat = $link.attr( 'cat' );
				var iconPath = '';
				
				if(cat) { 
					if(cat.indexOf('coffee')!=-1) {
						iconPath = this.path + 'coffee' + active + ".png";
						cat = 'coffee';
						
					} else if(cat.indexOf('event')!=-1) {
						iconPath = this.path + 'events' + active + ".png";
						cat = 'events';
						
					} else if(cat.indexOf('happy-hour')!=-1) {
						iconPath = this.path + 'happyhour' + active + ".png";
						cat = 'happyhour';
						
					} else if(cat.indexOf('listing')!=-1) {
						iconPath = this.path + 'listing' + active + ".png";
						cat = 'listing';
						
					} else if(cat.indexOf('misc')!=-1) {
						iconPath = this.path + 'uncategorized' + active + ".png";
						cat = 'uncategorized';
						
					} else if(cat.indexOf('parks')!=-1) {
						iconPath = this.path + 'parks' + active + ".png";
						cat = 'parks';
						
					} else if(cat.indexOf('restaurant')!=-1 || cat.indexOf('food')!=-1) {
						iconPath = this.path + 'restaurant' + active + ".png";
						cat = 'restaurant';
			
					} else if(cat.indexOf('school')!=-1) {
						iconPath = this.path + 'schools' + active + ".png";
						cat = 'schools';
						
					} else if(cat.indexOf('art')!=-1) {
						iconPath = this.path + 'art' + active + ".png";
						cat = 'art';
						
					} else if(cat.indexOf('shopping')!=-1) {
                                                iconPath = this.path + 'shopping' + active + ".png";
                                                cat = 'shopping';

                                        } else if(cat.indexOf('beer')!=-1) {
                                                iconPath = this.path + 'beer' + active + ".png";
                                                cat = 'beer';

                                        }
					else if(cat.indexOf('biking')!=-1) {
                                                iconPath = this.path + 'biking' + active + ".png";
                                                cat = 'biking';

                                        }
					else if(cat.indexOf('books')!=-1) {
                                                iconPath = this.path + 'books' + active + ".png";
                                                cat = 'books';

                                        }
					else if(cat.indexOf('camping')!=-1) {
                                                iconPath = this.path + 'camping' + active + ".png";
                                                cat = 'camping';

                                        }
					else if(cat.indexOf('family')!=-1) {
                                                iconPath = this.path + 'family' + active + ".png";
                                                cat = 'family';

                                        }
					else if(cat.indexOf('flickr')!=-1) {
                                                iconPath = this.path + 'flickr' + active + ".png";
                                                cat = 'flickr';

                                        }
					else if(cat.indexOf('gardening')!=-1) {
                                                iconPath = this.path + 'gardening' + active + ".png";
                                                cat = 'gardening';

                                        }
					else if(cat.indexOf('golf')!=-1) {
                                                iconPath = this.path + 'golf' + active + ".png";
                                                cat = 'golf';

                                        }
					else if(cat.indexOf('hiking')!=-1) {
                                                iconPath = this.path + 'hiking' + active + ".png";
                                                cat = 'hiking';

                                        }
					else if(cat.indexOf('kayaking')!=-1) {
                                                iconPath = this.path + 'kayaking' + active + ".png";
                                                cat = 'kayaking';

                                        }
					else if(cat.indexOf('markets')!=-1) {
                                                iconPath = this.path + 'markets' + active + ".png";
                                                cat = 'markets';

                                        }
					else if(cat.indexOf('movie')!=-1) {
                                                iconPath = this.path + 'movie' + active + ".png";
                                                cat = 'movie';

                                        }
					else if(cat.indexOf('music')!=-1) {
                                                iconPath = this.path + 'music' + active + ".png";
                                                cat = 'music';

                                        }
					else if(cat.indexOf('parks')!=-1) {
                                                iconPath = this.path + 'parks' + active + ".png";
                                                cat = 'parks';

                                        }
					else if(cat.indexOf('pets')!=-1) {
                                                iconPath = this.path + 'pets' + active + ".png";
                                                cat = 'pets';

                                        }
					else if(cat.indexOf('photo')!=-1) {
                                                iconPath = this.path + 'photo' + active + ".png";
                                                cat = 'photo';

                                        }
					else if(cat.indexOf('racing')!=-1) {
                                                iconPath = this.path + 'racing' + active + ".png";
                                                cat = 'racing';

                                        }
					else if(cat.indexOf('shopping')!=-1) {
                                                iconPath = this.path + 'shopping' + active + ".png";
                                                cat = 'shopping';

                                        }
					else if(cat.indexOf('sports')!=-1) {
                                                iconPath = this.path + 'sports' + active + ".png";
                                                cat = 'sports';

                                        }
						else if(cat.indexOf('tech')!=-1) {
                                                iconPath = this.path + 'tech' + active + ".png";
                                                cat = 'tech';

                                        }
					else if(cat.indexOf('theater')!=-1) {
                                                iconPath = this.path + 'theater' + active + ".png";
                                                cat = 'theater';

                                        }
					else if(cat.indexOf('transportation')!=-1) {
                                                iconPath = this.path + 'transportation' + active + ".png";
                                                cat = 'transportation';

                                        }
					else if(cat.indexOf('video')!=-1) {
                                                iconPath = this.path + 'video' + active + ".png";
                                                cat = 'video';

                                        }

					else if(cat.indexOf('youtube')!=-1) {
                                                iconPath = this.path + 'youtube' + active + ".png";
                                                cat = 'youtube';

                                        }
					else if(cat.indexOf('adult')!=-1) {
                                                iconPath = this.path + 'adult' + active + ".png";
                                                cat = 'adult';

                                        }
					else if(cat.indexOf('schools')!=-1) {
                                                iconPath = this.path + 'schools' + active + ".png";
                                                cat = 'schools';

                                        }
					else if(cat.indexOf('uncategorized')!=-1) {
                                                iconPath = this.path + 'uncategorized' + active + ".png";
                                                cat = 'uncategorized';

                                        }

					 else {
						iconPath = this.path + 'uncategorized' + active + ".png";
						cat = 'uncategorized';

					} 
					
					
				} else {
					iconPath = this.path + 'uncategorized' + active + ".png";
					cat = 'uncategorized';
				}
				color = cat;
				iconPath += '?postIcon=1';
			
				 if(!this.markers[postId]) {

                                icon = new GIcon();
                                icon.iconSize = new GSize(h,w);
                                icon.shadowSize = new GSize(0,0);
                                icon.iconAnchor = new GPoint(12, 12);

                                icon.image = iconPath; // this.path + color + active + ".png";

                                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[postId] = marker;
                                this.markers[postId].show();

//                              this.markers[postId].setImage(this.path + color + active + ".png");

				 $link.addClass( 'hq_idx_evtBound' ).mouseover( toolbox.delegate( this.onMouseOver, this, $link,  this.markers[postId]) )
                                .mouseout( toolbox.delegate( this.onMouseOut, this, $link,  this.markers[postId]) ) ;

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


                        } else {
				 $link.addClass( 'hq_idx_evtBound' ).mouseover( toolbox.delegate( this.onMouseOver, this, $link,  this.markers[postId]) )
                                .mouseout( toolbox.delegate( this.onMouseOut, this, $link,  this.markers[postId]) ) ;

                                this.markers[postId].show();
                                this.markers[postId].setImage(this.path + color + active + ".png?postIcon=1");

//                              continue;
                        }
	
			}
				this.markers[postId].hqColor = color;
		                this.markers[postId].hqActive = !!active;
		                if(this.markers[postId].hqActive)
                		        activeMarker = this.markers[postId];

			
		}


		//this.mmgr2.addMarkers(this.markers,7,17);
		//this.mmgr2.refresh();
		if(activeMarker != null) {
//			activeMarker.topMarkerZIndex();
		}
		
		if( len > 0 )
			this.setExtents();
			
		$j( '#postCountSubmit' ).hide( );
		$j( '#postCountSelect' ).change( function( ) { $j( '#postCountSubmit' ).click( ); } );
		
		console.groupEnd();
	},
	  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;
                $j('#map div').find('img[src*="postIcon"]').width(w).height(h);

        },

	
	onClick : function(evt, $link, marker) {
	//	marker.topMarkerZIndex();
	//	marker.setMouseOutEnabled(false);
	
		marker.setImage( this.path + marker.hqColor + "-active.png" );
                marker.hqActive = "-active";
	
		var href = $link.attr( 'href' );
		if( hq && hq.ajax )
			hq.ajax.loadLink( href );
		else
			window.location = href;
	},
	
	onListingsLoaded : function() {
		var nhId = parseInt( $j( '#nhId' ).val() );
		
		if( nhId && nhId != 'NaN' ) {
			$j.ajax({
				url: '/post-geo.php',
				data: { nhId : nhId},
				success: toolbox.delegate(this.onListingsLoadedCB, this),
				error: toolbox.delegate( this.onAjaxError, this)
			})
		}
		
		
	},
	
	
	onPrePaneLoad : function() {
		this.$balloon.hide();
	},
	
	
	onMouseOver : function( evt, $link, marker) {
		 var test = marker.Er;
//              var idx = $j(test).css('z-index');
                $j(test).css('z-index', 10000);

		$link.addClass( 'hover' );
		//var active = ( marker.hqActive ? "-active" : "" );
		var path = this.path +  marker.hqColor + "-active.png?postIcon=1&active=1";
		
		marker.setImage( path );
	//	marker.topMarkerZIndex();
		
		var agent = $link.attr('agentId');
		
		var icon = marker.getIcon();
		var iconHeight = 24; //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) +2;
		var v = 'u';
	

		if( top < 0 ) {
			top = px.y+15;
			v = 'l';
		}
		
		var width = 0;
		if(agent) {
			width = 380;
		} else {
			width = 280;
		}
		
		var left = px.x - 30;
		var h = 'r';
		
		if( left + width > windowWidth ) {
			h = 'l';
		}
		
		var url = '';
		
		if(agent) {
			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(false) 
				left = px.x - 380;
			else 
				left = px.x - 280;
		}
		
		
		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();
		
	},
	
	setExtents : function( evt ) {
		console.group( 'WpPosts::setExtents' );
		
		var $pane = $j( '#wpPostExtents' );
		
		var yMin = $pane.attr( 'yMin' );
		var yMax = $pane.attr( 'yMax' );
		var xMin = $pane.attr( 'xMin' );
		var xMax = $pane.attr( 'xMax' );
		

			if( yMin && yMax && xMin && xMax ) {

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


				hq.map.gMap.setCenter( bounds.getCenter() );
				hq.map.gMap.setZoom( this.gMap.getBoundsZoomLevel( bounds ) );
			}

		

		
		console.groupEnd();
	},
	
	onMouseOut : function( evt, $link, marker ) {
	//	var test = marker.Er;
          //      var idx = $j(test).css('z-index');
            //    $j(test).css('z-index', 0);

		$j('#map div').find('img[src*="&active"]').css('z-index', 0);


		$link.removeClass( 'hover' );
		var active = ( marker.hqActive ? "-active" : "" );
		marker.setImage( this.path + marker.hqColor + active + ".png?postIcon=1" );
//		marker.restoreMarkerZIndex();

		this.$balloon.hide();
		
	},
	
	updateZIndex : function( marker) {
		console.group( 'wpPosts::updateZIndex' );
		var res = GOverlay.getZIndex( marker.getPoint().lat() );
		console.groupEnd();
		return res;
	}
	
};

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