var villaShowState=1;
// used for array handling of marker icons creation details
// put them here because we get the data fr
function defMapIconDetails(name, fname, sname, x,y, sx,sy, ax,ay, wax,way, imap, tname) 
{
	this.name = name;	
	this.filename = fname;	this.sFilename = sname; 
	this.sizeX = x;	this.sizeY = y;
	this.shSizeX = sx;	this.shSizeY = sy;
	this.anchorX = ax;	this.anchorY = ay;
	this.windowAnchorX = wax;	this.windowAnchorY = way;
	this.imageMap = imap; this.transpFilename = tname;

	var icon = null;
	
	// copy constructor ???? doens't work
/*	this.defMapIconDetails = function(defmap)
	{
		this.name = defmap.name;	
		this.filename = defmap.fname;	this.sFilename = defmap.sname; 
		this.sizeX = defmap.x;	this.sizeY = defmap.y;
		this.shSizeX = defmap.sx;	this.shSizeY = defmap.sy;
		this.anchorX = defmap.ax;	this.anchorY = defmap.ay;
		this.windowAnchorX = defmap.wax;	this.windowAnchorY = defmap.way;
		this.imageMap = defmap.imap; this.transpFilename = defmap.tname;
		this.icon = null;
	}*/
	
	this.setName = function(newname) ///?? doesn't appear to work
	{
		// if a new name has been specified then, clear the icon image, just in case a new load is required
		this.name = newname;
		icon = null;
//		document.write(' cleare icon for:'+this.name);
		return this.name;
	}
	
	// return the GIcon for the name provided, if it doesn't exist then create it from the details provided
	this.getIconToUse = function()
	{
//		document.write(' requesting:'+this.name);
		if (!icon) // if not exist then create the icon
		{
//			document.write(' creating:'+this.name);
			icon = new GIcon();
			
			// determine whether the icon is a colour
			// if so (and it's not red) load it, by just changing the color in the filename
			switch(this.name)
			{
				case 'green':
				case 'blue':
				case 'orange':
					var search = new RegExp("red");
					this.filename = this.filename.replace(search, name);
				default:
			}
		
			icon.image = this.filename;
			if (this.sFilename)
				icon.shadow = this.sFilename ;
			icon.iconSize = new GSize(this.sizeX,this.sizeY);
			if (this.shSizeX)
				icon.shadowSize = new GSize(this.shSizeX,this.shSizeY );
			icon.iconAnchor = new GPoint(this.anchorX,this.anchorY);
			icon.infoWindowAnchor = new GPoint(this.windowAnchorX,this.windowAnchorY);
	//		if (source .imageMap )
	//								icon.imageMap  = ....
			if (this.transparent)
				icon.transparent = this.transpFilename;	
			
			gicons[this.name] = icon;
		}
		
		// now use the icon to create the marker	
		return icon;
	}
}

function showMap(nm, forGrabbing)
{
    var map = new GMap(document.getElementById("map"));
	globmap = map;

	if (!forGrabbing)
	{
	    map.addControl(new GLargeMapControl());
	    map.addControl(new GMapTypeControl());
	}
    
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    
    // need to preload a center point in order to create markers ?????
    // thus don't delete this, it will be overridden later anyway
    map.centerAndZoom(new GPoint(-81.581297,28.418712),6);

    // now use the tags to create markers
	for (var i = 0; i < name.length; i++) 
	{
		// need to go through and create all the markers, 
		// while creating, only add the marker to the sidebar if 'sbarByDefault'
		var iconToUse = null;
		var addToSideBar = sbarByDefault[i];
		var displayMarker = dispMarker[i];
		
		gpoint[i] = new GPoint(lon[i],lat[i]);
		
		// if the marker uses a specific icon then look to use/create
		if (iconname[i])
		{
			iconToUse = gicondetails[iconname[i]].getIconToUse();
		}
		
		if (name[i]==nm )						
		{
			// make sure that if the name's been passed in then add to sidebar
			//  & use the default (large) gmap marker icon
			addToSideBar=1;
			if (name[i]!='spv')	// make sure never to override the villa icon
				iconToUse = null;	// this will override the pre-defined icon for the marker
			displayMarker = 1;
		}
					
		// now create the marker and add to the overlay;
		var marker = createMarker(map,i,gpoint[i],name[i],html[i],iconToUse,addToSideBar);
		// now add to the map
		if (displayMarker )
		{
			map.addOverlay(marker);		
		
			if (forGrabbing&& showToolTip[i])
			{
				marker.setTooltipHiding(false);
				marker.showTooltip();
			}
		}

	}
	// ok all markers added
	// Now spring the villa marker into a flashing one
	if (!forGrabbing)
		setTimeout("flashMarkerNum("+gmarkerNames['spv']+")",3300);
}	    

function addSidebar(id)
{	
	// add the sidebar - by this time the sidebar has already been populated, just need to wrap the table
	//  around it and add class
	sidebar_html = '<table width="100%">'+sidebar_html+'</table>';
    document.getElementById(id).innerHTML = '<div class="sidebar">' + sidebar_html + '</div>';
}	    

function getDirectionsFor(i)
{
	var directions="";
	// determine whether the marker is an airport, if so then add a directions link
	if (iconname[i]=='plane' || iconname[i]=='blue')
	{
		directions = "<br>Directions: <a target='_blank' href='http://maps.google.com/maps?f=d&hl=en&saddr=";
		directions += name[i]; // currently this is easy because all the aiports name are their actual airport codes
		directions += "&daddr=heritage+pass,+33896&btnG=Search'> to the Shawpad Villa</a>";
	}
	else
	{
		if (mapType=='guest' && name[i]!='spv')
		{
			directions = "<br>Directions: <a target='_blank' href='http://maps.google.com/maps?f=d&hl=en&daddr=";
			directions += lat[i] + "," + lon[i]; // currently this is easy because all the aiports name are their actual airport codes
			directions += "&saddr=heritage+pass,+33896&btnG=Search'> from the Shawpad Villa</a>";
		}
	}
	return directions;
}	

function getGuestPicLinkFor(i)
{
	var guestPics ="";
	// determine whether the marker is an airport, if so then add a directions link
	if (guestLink[name[i]])
	{
		guestPics = "<p>See some <a target='_blank' href='" 
		guestPics += guestLink[name[i]];
		guestPics += "'>pictures</a> from a<br>recent guest visit.</p>";
	}
	return guestPics ;
}	

// A function to create the marker and set up the event window
function createMarker(map,i,point,name,html,icon,addToSideBar)
{
//	var marker = new GMarker(point, icon);
	var marker = new PdMarker(point, icon);
	marker.setTooltip(descrname[i]);
	
	var directions = getDirectionsFor(i);
	var guestPics = getGuestPicLinkFor(i);
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml('<div style="white-space:nowrap;">' + html + directions + guestPics + '</div>');
	});
	// save the info we need to use later for the sidebar
	gmarkers[i] = marker;
	gmarkerNames[name] = i;

	if (addToSideBar)
	{
		// add a line to the sidebar html
		// each line is a new row
		sidebar_html += '<tr><td class="sidebar">';
		sidebar_html += getHtmlMarkerIcon(iconname[i],descrname[i]);
		sidebar_html += '&nbsp;</td><td class="sidebar"><a href="javascript:zoomToBoundsWithVilla('+ i + ')">';
		sidebar_html += descrname[i] + '</a></td></tr>';
	}
	return marker;
}

function centreMap(name)
{
	zoomToBoundsWithVilla(gmarkerNames[name]);
}


// This function picks up the click and opens the corresponding info window
// this is used for the hyperlinks on the sidebar
function zoomToBoundsWithVilla(i) 
{
	var visible=0;
	
	// close any old infowindow that's open
	globmap.closeInfoWindow();
	
	// the first point is a predefined 'map center' so no repositioning required
	if (i==0)
		point = gpoint[i];
	else
		// zoom to a point that you can see both the selected marker and the villa
		point = new GPoint((gpoint[i].x+gpoint[villaIndex].x)/2, (gpoint[i].y+gpoint[villaIndex].y)/2);
		
	globmap.centerAtLatLng(point);

	if (html[i])
	{
		var list = new Array();
		var directions = getDirectionsFor(i);
		var guestPics = getGuestPicLinkFor(i);
		
		list[0] = gpoint[i];
		list[1] = gpoint[villaIndex];
		resizeMap(globmap,list);
		gmarkers[i].openInfoWindowHtml('<div style="white-space:nowrap;">' + html[i] + directions + guestPics + '</div>');
	}
	else
		globmap.zoomTo(zoom[i]);

	// need to do further checks, becuase of the bubble open delay time
	setTimeout("zoomToShowVilla("+i+")",1000);	
}

function flashMarkerNum(markerNum)
{
	villaShowState = !villaShowState;
	gmarkers[markerNum].display(villaShowState);
	setTimeout("flashMarkerNum("+markerNum+")",1500 + villaShowState*3500);
}

function zoomToShowVilla(i)
{
	var bounds = globmap.getBoundsLatLng();    
	if ((gpoint[villaIndex].x > bounds.maxX) || (gpoint[villaIndex].x < bounds.minX) 
		|| (gpoint[villaIndex].y > bounds.maxY) || (gpoint[villaIndex].y < bounds.minY))    
	{
		globmap.zoomTo(globmap.getZoomLevel()+1);
		setTimeout("zoomToShowVilla("+i+")",200);
	}	
}

// this adds the requested legend marker to the div specified by the id
function addLegend(divElement, color, name)
{
	var html = getHtmlMarkerIcon(color, name);
	html += '<input type="checkbox" name="Attractions" id="' +color+ '" onclick="markersOnOff(\'';
	html += color+ '\')" checked="checked" />' +name;
    document.getElementById(divElement).innerHTML += html;
}

// this add's all the legends, curently they need to be manually specified
function addMarkerLegends(divArea)
{
	if (gicondetails['red'])
		addLegend(divArea,'red','Attractions');
	if (gicondetails['green'])
		addLegend(divArea,'green','Golf');
	if (gicondetails['orange'])
		addLegend(divArea,'orange','Shops  ');
	if (gicondetails['blue'])
		addLegend(divArea,'blue','Airports');
	if (gicondetails['airport'])
		addLegend(divArea,'airport','Airports');
	if (gicondetails['white'])
		addLegend(divArea,'white','Road Tolls');
}

function getHtmlMarkerIcon(iconName, name)
{
	var html="";
	if (gicondetails[iconName])
	{
		// make sure the icon has been manipulated if necessary for the color
		gicondetails[iconName].getIconToUse();
		html = '<img src="';
		html += gicondetails[iconName].filename;
		html += '" width="12" height="20" title="' +name+ '" alt="' +name+ '" />';
	}
	return html;
}

function markersOnOff(color)
{
	globmap.closeInfoWindow();
	var state = document.getElementById(color).checked;
	{ // hide/show the markers
	  for (var i=0;i<iconname.length;i++) 
	  {
	     if (iconname[i]==color)  
	     {
//	        globmap.removeOverlay(gmarkers[i]);
			gmarkers[i].display(state);

	     }
	  }
	}
}

function resizeMap( map, points ) {
  var minLong = 999;
  var minLat = 999;
  var maxLong = -999;
  var maxLat = -999;
  
  // Get the current map width/height
  var size = map.getSpanLatLng();
  var mapWidth = size.width;
  var mapHeight = size.height;
  var baseWidth = mapWidth;
  var baseHeight = mapHeight;
  
  // Figure out the elemental unit (depends on the size of the map)
  // You will need to re-run resizeMap() if the size of the map changes.
  if ( map.getZoomLevel() > 0 ) {
    baseWidth /= Math.pow( 2, map.getZoomLevel() );
    baseHeight /= Math.pow( 2, map.getZoomLevel() );
  }
  
  // Find the max/min points
  for ( var i = 0; i < points.length; i++ ) {
    if ( points[i].x < minLong ) minLong = points[i].x;
    if ( points[i].x > maxLong ) maxLong = points[i].x;
    if ( points[i].y < minLat ) minLat = points[i].y;
    if ( points[i].y > maxLat ) maxLat = points[i].y;
  }
  
  // Find the optimal Width Zoom
  var wZoom = 0;
  var w = Math.abs( maxLong - minLong );
  for ( var i = 1; i < 16; i++ ) {
    if ( baseWidth > w ) break;
    baseWidth *= 2;
    wZoom = i;
  }
  
  // Find the optimal Height Zoom
  var hZoom = 0;
  var h = Math.abs( maxLat - minLat );
  for ( var i = 1; i < 16; i++ ) {
    if ( baseHeight > h ) break;
    baseHeight *= 2;
    hZoom = i;
  }
  
  // Reposition
  map.centerAndZoom(
    new GPoint( ( minLong + maxLong ) / 2, ( minLat + maxLat ) / 2 ),
    ( wZoom > hZoom ? wZoom : hZoom )
  );
}

function cloneObject(what) {
    for (i in what) {
        if (typeof what[i] == 'object') {
            this[i] = new cloneObject(what[i]);
        }
        else
            this[i] = what[i];
    }
}


