Type.registerNamespace("PREA");
Type.registerNamespace("PREA.Houston");
Type.registerNamespace("PREA.Houston.Google");
Type.registerNamespace("PREA.Houston.Google.Map");

PREA.Houston.Google.Map.Neighbourhood = function(){};

PREA.Houston.Google.Map.Neighbourhood.prototype = 
{	
	draw : function( lat, lng )
	{	
		this.neighbourhoodMap = new GMap2( divMap );
		if( lat == null || lng == null ) // use address if no lat or lng available 
		{
			this.neighbourhoodMap.setCenter( new GLatLng( 0, 0 ), zoomLevel );
			var cg = new GClientGeocoder();
			cg.getLatLng( address.value, this.addMarker );
		}
		else //when both lat and lng have values 
		{
			var p = new GLatLng( lat, lng );
			this.neighbourhoodMap.setCenter( p, zoomLevel );
			this.addMarker( p );
 		}
	},
	
	// This function adds the point to the map
	addMarker : function( p )
	{
		// add the marker for the property
		var pruIcon = new GIcon( G_DEFAULT_ICON );		
		pruIcon.image = iconImageUrl;  
		pruIcon.iconSize = new GSize( 22, 28 );              
		pruIcon.iconAnchor = new GPoint( 4, 28);
        pruIcon.shadow = ""; //a hack to turn off shadow
		var markerOptions = { icon : pruIcon };	
    	
		this.listingMarker = new GMarker( p, markerOptions );

		gmn.neighbourhoodMap.addOverlay( this.listingMarker );
		gmn.neighbourhoodMap.addControl( new GLargeMapControl() );	
		gmn.neighbourhoodMap.addControl( new GMapTypeControl() );
		gmn.neighbourhoodMap.setCenter( p, zoomLevel );
	},
	
	checkBizType : function( bizType )
	{
		switch ( bizType )
		{
			case "School":
				return document.getElementById( localSchool ).checked;
				break;
			case "Grocery Stores":
				return document.getElementById( groceryStores ).checked;
				break;
			case "Parks":
				return document.getElementById( parks ).checked;
				break;
			case "Restaurants":
				return document.getElementById( restaurants ).checked;
				break;
			case "Gas Stations":
				return document.getElementById( gasStations ).checked;
				break;
			default: 
				return false;
				break;
		}
	},		

	display : function( bizType )
	{
		if ( this.checkBizType( bizType ) )
		{   
			searchType = bizType;
			search = new GlocalSearch(); 
			search.setCenterPoint( this.neighbourhoodMap );
			search.setSearchCompleteCallback( null, this.onSearch ); 
			search.execute( bizType );
		}
		else
		{
			var letter = this.getMarkerLetter( bizType );
			this.removeMarker( letter );
		}
	},
	
	onSearch : function() 
	{ 
		for( var i = 0; i < search.results.length; i++ ) 
		{ 
			var r = search.results[ i ];
			var p = new GPoint( parseFloat( r.lng ), parseFloat( r.lat ) );
			gmn.neighbourhoodMap.addOverlay( gmn.createMarker( p, r ) );
		} 
	},
	
	createMarker : function ( point, result ) 
	{
		var icon = new GIcon( G_DEFAULT_ICON );
		icon.image = imgDir + "map_marker_" + this.getMarkerLetter( searchType ) + ".png";
		icon.iconSize = new GSize(20, 34);
		icon.shadow = ""; //a hack to turn off shadow
		var markerOptions = 
			{ 
				icon: icon, 
				clickable: true
			};

		var marker = new GMarker( point, markerOptions );

		var pn;
		if ( result.phoneNumbers )
		{
			pn = result.phoneNumbers[0]["number"];
		}
		else
		{
			pn = "N/A";
		}
		var popHtml = "<span><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"ts\" style=\"width: 200px; max-width: 300px\">"
		+ "<tr><td align=\"left\" class=\"popmap\"><b>" + result.title + "</b></td><tr>"
		+ "<tr><td align=\"left\" class=\"popmap\">" + pn + "</td><tr>"
		+ "<tr><td align=\"left\" class=\"popmap\">" + result.streetAddress + "</td><tr>"
		+ "<tr><td align=\"left\" class=\"popmap\">" + result.city
		+ (result.city != "" ? ", " : "") + result.region + "</td><tr>"
		+ "<tr><td align=\"left\" class=\"popmap\"><a href = \"" + result.ddUrlToHere + "\">Directions To</a> - <a href = \"" + result.ddUrlFromHere   + "\">From</a></td><tr>"
		+ "<tr><td align=\"left\" class=\"popmap\"><a href = \"" + result.url + "\">Write a Review</a>&nbsp;|&nbsp;<a href = \"" + result.url + "\">More Info</a></td><tr>"
		+ "</table></span>";

		GEvent.addListener
		( 
			marker, 
			"click", 
			function() 
			{
				marker.openInfoWindowHtml( popHtml );
			}
		);
		markers.push( marker );
		return marker;		
	},

	removeMarker : function( letter )
	{
		for( i = 0; i < markers.length; i++ )
		{
			var icon = markers[i].getIcon();
			if( icon.image.match( "map_marker_" + letter + ".png" ) )
			{
				this.neighbourhoodMap.removeOverlay( markers[i] );
			}
		}	
	},
	    
	clearMap :	function()
	{
		this.removeMarker( "A" );
		this.removeMarker( "B" );
		this.removeMarker( "C" );
		this.removeMarker( "D" );
		this.removeMarker( "E" );

		document.getElementById( localSchool ).checked = false;
		document.getElementById( groceryStores ).checked = false;
		document.getElementById( parks ).checked = false;
		document.getElementById( restaurants ).checked = false;
		document.getElementById( gasStations ).checked = false;
	},
			
	getMarkerLetter : function( bizType )
	{
		switch ( bizType )
		{
			case "School":
			return "A";
			break;
			case "Grocery Stores":
			return "B";
			break;
			case "Parks":
			return "C";
			break;
			case "Restaurants":
			return "D";
			break;
			case "Gas Stations":
			return "E";
			break;
			default: "def";
			break;
		}
	}
};
PREA.Houston.Google.Map.Neighbourhood.registerClass("PREA.Houston.Google.Map.Neighbourhood");

PREA.Houston.Google.Map.Portfolio = function(){};
	
PREA.Houston.Google.Map.Portfolio.prototype =
{
	draw : function()
	{
		this.portfolioMap = new GMap2( divMap );
		//this.directions = new GDirections(this.portfolioMap, document.getElementById("divDirectionsResult"));
		this.portfolioMap.addControl( new GLargeMapControl() );	
		this.portfolioMap.addControl( new GMapTypeControl() );
	    this.wayPoints = new Array();
        this.totalMarkers = new Array();

		for ( mapPoint in mapPoints   )
		{
			var p = mapPoints[ mapPoint ];
			var posn = new GLatLng( p["posn"][0], p["posn"][1] );
			points.push( posn );
		}		
		var bounds = new GBounds( points );
		var llbounds = new GLatLngBounds();
		var mid = bounds.mid();
		var llmid = new GLatLng( mid.y, mid.x );
		this.portfolioMap.setCenter( llmid, zoomLevel ); //temp center to draw markers

		for ( mapPoint in mapPoints )
		{
			var p = mapPoints[ mapPoint ];			
			function createMarker( p ) 
			{
				var titlearray = p["title"].split( " " );
				var iconlabel = titlearray[0];
				var posn = new GLatLng( p["posn"][0], p["posn"][1] );
				var pruIcon = new GIcon( G_DEFAULT_ICON );
				pruIcon.image = p["icon"][0];  
				pruIcon.iconSize = new GSize( p["icon"][1], p["icon"][2] );
				pruIcon.iconAnchor = new GPoint( 0, 22);
				pruIcon.infoWindowAnchor = new GPoint( 7, 3);
				pruIcon.shadow = ""; //a hack to turn off shadow
				markerOptions = 
					{ 
						title: p["title"],
						icon: pruIcon, 
						clickable: true,
						labelText: iconlabel,
						labelClass: "MapLabel",
						labelOffset: new GSize( (iconlabel.length == 1) ? 2 : -1 , -22)
					};	
				var m = new LabeledMarker( posn, markerOptions ); 
				llbounds.extend( m.getLatLng() );
				
				GEvent.addListener
				( 
					m, 
					"click", 
					function() 
					{
						m.openInfoWindowHtml( p["popupL"] );
					}
				);		
				gmp.totalMarkers.push(m);
				return m;
			}
			
			this.portfolioMap.addOverlay( createMarker( p ) );
		}				
		this.portfolioMap.setCenter( llmid, this.portfolioMap.getBoundsZoomLevel( llbounds ) );
	},	
	popInfoWindow : function ( addressIndex )
	{
		var mapPoint = mapPoints[ addressIndex - 1 ];
		this.totalMarkers[addressIndex - 1].openInfoWindowHtml( mapPoint["popupL"] );
	},
	GetDirections : function()
	{
	    //this.portfolioMap.clearOverlays()
	    var addressText = document.getElementById("txtAddress");
		this.totalAddresses = 1;
		var currentAddress = 1;

	    while (addressText != null)
        {
	        addressText = document.getElementById("txtAddress" + this.totalAddresses);
	        this.totalAddresses++;
        }
        this.totalAddresses--;
        addressText = document.getElementById("txtAddress");
	    
	    while (addressText != null)
	    {
			this.GetSingleDirection(currentAddress, addressText.value);
	        addressText = document.getElementById("txtAddress" + currentAddress);
	        currentAddress++;
	    }
	},
	GetSingleDirection : function(index, address)
	{
	    // this is a hack to get JS to accept 2 params on a callback.
		var cg = new GClientGeocoder();
	    var addPoint = function(p)
        {
            gmp.wayPoints[index-1] = p;
                        	    
            if (gmp.wayPoints.length == gmp.totalAddresses)
            {
                //TODO this is where u'd add the travel by foot/road
                gmp.directions.loadFromWaypoints(gmp.wayPoints);
            }
        }	    
        cg.getLatLng( address, addPoint );
	}
};
PREA.Houston.Google.Map.Portfolio.registerClass("PREA.Houston.Google.Map.Portfolio");

PREA.Houston.Google.Map.Search = function(){};

PREA.Houston.Google.Map.Search.prototype =
{
	setType : function ( mapTypeName )
	{
		switch ( mapTypeName.toLowerCase() )
		{
			case "satellite":
				this.searchMap.setMapType( G_SATELLITE_MAP );
				break;
			case "hybrid":
				this.searchMap.setMapType( G_HYBRID_MAP );
				break;
			case "map":
			default:
				this.searchMap.setMapType( G_NORMAL_MAP );
				break;
		}
	},

	config : function() 
	{	
		var mapTypeCookieValue = GetCookie( G_COOKIE_MAP_TYPE );
		var mapTypeName = ( mapTypeCookieValue == '' || mapTypeCookieValue == null ) ? G_NORMAL_MAP.getName() : mapTypeCookieValue; 
		this.setType( mapTypeName );
		
		//the listener must be set after the initial map type set up, to avoid the unneccessary event fire
		GEvent.addListener
		( 
			this.searchMap, 
			"maptypechanged", 
			function() 
			{
				SetCookieforMap( G_COOKIE_MAP_TYPE, gms.searchMap.getCurrentMapType().getName() );
			}
		);
	},

	resize : function() 
	{
		if ( GetCookie( G_COOKIE_MAP_SIZE ) == "L" )
		{
			divMap.style.width = G_WIDTH;
			divMap.style.height = G_HEIGHT;
			lnkSize.innerHTML = 'Expand Map Size';
			SetCookieforMap( G_COOKIE_MAP_SIZE, 'S');
		} 
		else 
		{
			divMap.style.width = G_EXPAND_WIDTH;
			divMap.style.height = G_EXPAND_HEIGHT;
			lnkSize.innerHTML = 'Reduce Map Size';
			SetCookieforMap( G_COOKIE_MAP_SIZE, 'L');
		}
		
		//redraw map
		this.draw();
	},

	initStyle : function() 
	{
		if ( GetCookie( G_COOKIE_MAP_SHOW ) != "Y" )
		{
			ShowMapFooter.style.display = "none";
			HiddenMapFooter.style.display = "block";
		} 
		else 
		{
			ShowMapFooter.style.display = "block";
			HiddenMapFooter.style.display = "none";
		}
	},

	initSize : function() 
	{
		if ( GetCookie( G_COOKIE_MAP_SIZE ) == "L" )
		{
			divMap.style.width = G_EXPAND_WIDTH;
			divMap.style.height = G_EXPAND_HEIGHT;
			lnkSize.innerHTML = 'Reduce Map Size';
		} 
		else 
		{
			divMap.style.width = G_WIDTH;
			divMap.style.height = G_HEIGHT;
			lnkSize.innerHTML = 'Expand Map Size';
		}
	},
	
	hide : function() 
	{
		pnlMap.className = stylHide;
		ShowMapFooter.style.display = "none";
		HiddenMapFooter.style.display = "block";
		SetCookieforMap( G_COOKIE_MAP_SHOW, 'N');	
	},

	show : function() 
	{
		pnlMap.className = stylShow;
		ShowMapFooter.style.display = "block";
		HiddenMapFooter.style.display = "none";
		SetCookieforMap( G_COOKIE_MAP_SHOW, 'Y' );
		this.draw();
	},
	
	draw : function()
	{
		this.searchMap = new GMap2( divMap );

		//decorate the map with zoom and type selector
		this.searchMap.addControl( new GSmallMapControl() );	
		this.searchMap.addControl( new GMapTypeControl() );

		//find and set the center of the map based on map points
		var posns = new Array();
		for ( mapPoint in mapPoints )
		{
			var p = mapPoints[mapPoint];
			var posn = new GLatLng( p["posn"][0], p["posn"][1] );
			posns.push( posn );
		}

		var bounds = new GBounds( posns );
		var llbounds = new GLatLngBounds();
		var mid = bounds.mid();
		var llmid = new GLatLng( mid.y, mid.x );
		this.searchMap.setCenter( llmid, zoomLevel ); //temp center to draw markers

		//set icon, listener for each marker 
		for ( mapPoint in mapPoints   )
		{
			var p = mapPoints[ mapPoint ];
			function createMarker( p ) {
				//set icon
				var titlearray = p["title"].split( " " );
				var iconlabel = titlearray[0];
				var posn = new GLatLng( p["posn"][0], p["posn"][1] );
				var pruIcon = new GIcon();				
				pruIcon.image = p["icon"][0];  
				pruIcon.iconSize = new GSize( p["icon"][1], p["icon"][2] );              
				pruIcon.iconAnchor = new GPoint( 0, 22);
				pruIcon.infoWindowAnchor = new GPoint( 7, 3);
				pruIcon.shadow = ""; //a hack to turn off shadow
				markerOptions = 
					{ 
						title: p["title"],
						icon: pruIcon, 
						clickable: true,
						labelText: iconlabel,
						labelClass: "MapLabel",
						labelOffset: new GSize( (iconlabel.length == 1) ? 2 : -1 , -22)
					};	
				
				var m = new LabeledMarker( posn, markerOptions ); 
				llbounds.extend( m.getLatLng() );
				//set icon click listener
				GEvent.addListener
				( 
					m, 
					"click", 
					function() 
					{
						m.openInfoWindowHtml( p["popupL"] );
					}
				);				
				return m;
			}				

			this.searchMap.addOverlay( createMarker( p ) );
		}	
		
		this.searchMap.setCenter( llmid, this.searchMap.getBoundsZoomLevel( llbounds ) );

		this.config();

	    var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

        if (IE6 == true)
        {
		    pnlMap.className = stylShow;
		    ShowMapFooter.style.display = "block";
		    HiddenMapFooter.style.display = "none";
		    SetCookieforMap( G_COOKIE_MAP_SHOW, 'Y' );
		}
		//it is unfortunate to do this last to simplify the exception handling of javascript
		else if( GetCookie( G_COOKIE_MAP_SHOW ) != "Y" )
		{		   
			this.hide();
		}		
	}
};
PREA.Houston.Google.Map.Search.registerClass("PREA.Houston.Google.Map.Search");
