// Display the correct number of items in the sidebar.
// Also makes sure the "Next" and "Prev" links change the sidebar correctly.
function showItems(num, place) {
   current_sidebar = "<ul>";
   var num = parseInt(num);
   var catset = 0;
   for(var i = 0; (i < num) && (i + place < sidebar_htmls.length) ; i++) {
       var j = i + place;
       current_sidebar += sidebar_htmls[j];
   }
   sidebar_place = parseInt(place);
   prevplace = sidebar_place - num;
   nextplace = sidebar_place + num;
   current_sidebar += '<br />';
   if(place > 0) {
       current_sidebar += "<a href=\"javascript:showItems(sidebar_num, prevplace)\">Previous</a>\n";
   }
   if(nextplace < sidebar_htmls.length) {
       current_sidebar += "<a href=\"javascript:showItems(sidebar_num, nextplace)\">Next</a>\n";
   }
   current_sidebar += "</ul>\n";
   document.getElementById("google_maps_sidebar").innerHTML = current_sidebar;
}

// This function picks up the click and opens the corresponding info window
function myclick(i,lng,lat,zoom) {
  try {
    map.closeInfoWindow();
    tooltipMouseout();
  } catch(err) {}
  map.setCenter(new GLatLng(lat,lng),zoom);
  if(!infoWindowsHtml[i]) {
     if(safariCompat == 1) {
          infoWindowsHtml[i] = infoHtml(infoWindows[i]);
     } else {
          infoWindowsHtml[i] = xsltProcess(infoWindows[i], xmlHttp.responseXML);
     }
  }
  markers[i].openInfoWindowHtml(infoWindowsHtml[i]);
 }
 
 
 // This function picks up the click and opens the corresponding info window
function setcountrycenter(lng,lat,zoom) {
  try {
    map.closeInfoWindow();
    tooltipMouseout();
  } catch(err) {}
  map.setCenter(new GLatLng(lat,lng),zoom);
 }
 
 
 //This function initializes the tooltips. Without it tooltips will not showup.
 function initTooltip(show) {
    if(show != 0) {
          tooltip = document.createElement("div");
	      map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
          tooltip.style.visibility="hidden";
    }
 }
 
 // The sidebar utilizes these functions to open/close tooltips when the mouse hovers over the sidebar link.
 function tooltipMouseover(i) {
  if(tooltipShow != 0 ) showTooltip(markers[i])
 } 
 function tooltipMouseout() {
  if(tooltipShow != 0 ) tooltip.style.visibility="hidden";
 }
 
 // This is the Safari compatibility function, that supposedly doesn't work.
 function infoHtml(info) {
    var name = GXml.value(info.getElementsByTagName("ref")[0]);
    var address = GXml.value(info.getElementsByTagName("address")[0]);
    var city = GXml.value(info.getElementsByTagName("city")[0]);
    var state = GXml.value(info.getElementsByTagName("state")[0]);
    var zipcode = GXml.value(info.getElementsByTagName("zipcode")[0]);
	var html = '<div class="infoWindow"><b>' + name + '</b><br />' + address + '<br />' + city + ', ' + state + ' ' + zipcode + '<br /><br /></div>';
    return html;
 }
 
 // This function grabs the name of a category using the catid and then spits out the appropriate sidebar html.
 function getCatName(singleCat,allCats, prevCat) {
    catName = "";
	for (var i = 0; i < allCats.length; i++) {
        var catId = allCats[i].getAttribute("id");
        if(catId == singleCat && (catId != prevCat || sidebar_htmls.length % sidebar_num == 0) && sidebar_showcat != 0) {
           catName = allCats[i].getAttribute("name");
           //var catTitle = "<div class=\"sidebar_category\"><u>" + catName + "</u></div>"
           return catName;
           break;
        }
    }
    return catName;
 }

 // This function creates the marker, the sidebar html, the event listeners, the tooltip, etc
 // It also puts the marker onto the map. It does it all.
 function createMarker(info, i) {
    var localId = info.getAttribute("id");
    var localType = info.getAttribute("type");
    var localName = GXml.value(info.getElementsByTagName("ref")[0]);
	var localPrice = GXml.value(info.getElementsByTagName("price")[0]);
	var localCur_from = GXml.value(info.getElementsByTagName("cur_from")[0]);
	var localCity = GXml.value(info.getElementsByTagName("city")[0]);
	var localCountry = GXml.value(info.getElementsByTagName("country")[0]);
    var localCatid = info.getAttribute("category");
    var localDrag = info.getAttribute("draggable");
    var localLat = info.getAttribute("lat");
    var localLng = info.getAttribute("lng");
    var localTitle = getCatName(localCatid,xmlCats,prevcat);
    sidebar_htmls.push('<table border="0" width="100%" ><tr style="cursor:pointer;" >'+ '<td width="5%">' + i + '</td>'+ '<td width="30%"><a href="javascript:myclick('+i+',' + localLng + ',' + localLat +',15)" onmouseover="tooltipMouseover('+i+')" onmouseout="tooltipMouseout()">' + localCity + '</a></td>'+ '<td width="30%">' + localCountry + '</td>'+ '<td width="30%">' + localPrice + '</td>'+ '<td>' + localCur_from+ '</td>' + '</tr></table>');
    //var catIcon = parseInt(getCatIcon(localCatid));
    var point = new GLatLng(parseFloat(localLat),parseFloat(localLng));
    
	if (localCatid == 28){
		var catIcon = 1;
	}
	if (localCatid == 29){
		var catIcon = 2;
	}
	if (localCatid == 30){
		var catIcon = 7;
	}
	if (localCatid == 31){
		var catIcon = 8;
	}
	if (localCatid == 32){
		var catIcon = 9;
	}
	if (localCatid == 33){
		var catIcon = 10;
	}
	
	if(localDrag == 1) {
        var marker = new GMarker(point,{icon:baseIcon[catIcon], draggable: true});
    } else {
        var marker = new GMarker(point,{icon:baseIcon[catIcon]});
    }
    
    if(tooltipShow != 0 ) {
        marker.tooltip = '<div class="tooltip">'+localPrice+' '+ localCur_from +' </div>';
        GEvent.addListener(marker,"mouseover", function() {
            showTooltip(markers[i]);
        });        
        GEvent.addListener(marker,"mouseout", function() {
            tooltip.style.visibility="hidden"
        });
    }
    GEvent.addListener(marker, "click", function() {
       if(safariCompat == 1) {
            infoWindowsHtml[i] = infoHtml(info);
       } else {
            infoWindowsHtml[i] = xsltProcess(info, xmlHttp.responseXML);
       }
       marker.openInfoWindowHtml(infoWindowsHtml[i]);
    });
    
	map.addOverlay(marker);
	
	if(localDrag == 1) marker.enableDragging();
    prevcat = localCatid;
    return marker;
 }

 // This shows the tooltip when the mouse hovers over a marker or a sidebar link.
 function showTooltip(marker) {
   	tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + (1.2*width), offset.y - point.y -anchor.y)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
    // Code From PdMarkers www.pixeldevelopment.com/pdmarker.asp
    var b = 75;
	var c = b / 100;
	if (tooltip)
	{
		if(typeof(tooltip.style.filter)=='string'){tooltip.style.filter='alpha(opacity:'+b+')';}
		if(typeof(tooltip.style.KHTMLOpacity)=='string'){tooltip.style.KHTMLOpacity=c;}
		if(typeof(tooltip.style.MozOpacity)=='string'){tooltip.style.MozOpacity=c;}
		if(typeof(tooltip.style.opacity)=='string'){tooltip.style.opacity=c;}
	}
	// end of PdMarkers code 
 }
 
 // This function is used to place certain markers based on category id.
 function checkCat(catLookup,carray) {
    if(carray.length != 0) {
        for (i=0;i < carray.length;i++) {
            if(carray[i] == catLookup) {
                return true;
                break;
            }
        }
        return false;
    } else {
         return true;
    }
 }
 
 // This function is used to place certain markers based on marker id.
 function checkPoint(pointLookup,pointArray) {
    if(pointArray.length != 0) {
		for (i=0;i < pointArray.length;i++) {
			if(pointArray[i] == pointLookup) {
				return true;
				break;
			}
		}
		return false;
    } else {
		return true;
	}
 }
 
 // This function gets the gicon associated with each category
 function getCatIcon(singleCat) {
    for(var i=0; i < xmlCats.length; i++) {
        var catId = xmlCats[i].getAttribute("id");
        if(catId == singleCat) {
            if(xmlCats[i].getAttribute("gicon")) {
                var gicon = xmlCats[i].getAttribute("gicon");
                return gicon;
                break;
            }
        }
    }
    return 0;
 }
 
 //  This function to adjusts the positioning of the overview map (minimap)
 function positionOverview(x,y) {
     omap = document.getElementById("map_overview");
     //Place in a div container outside of the map
     var place=document.getElementById("overview_map_holder");
     omap.style.position = "relative";
     omap.style.left = "0px";
     omap.style.top = "0px";
     place.appendChild(omap);        

     // GControlPosition to place the overview map within the map.
     // Currently doesn't work in Internet Explorer
     //var pos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0,0));
     //pos.apply(document.getElementById("map_overview"));
     //map.getContainer().appendChild(document.getElementById("map_overview"));
        
     // == restyling ==
     omap.firstChild.style.border = "1px solid gray";

     omap.firstChild.firstChild.style.left="4px";
     omap.firstChild.firstChild.style.top="4px";
     omap.firstChild.firstChild.style.width="190px";
     omap.firstChild.firstChild.style.heigh="190px";
     
 }

/* Convert degress to radians */
function deg2rad(deg) {
  return deg / (180 / Math.PI);
}

/* Calculate distance between two points in meters 
   Where a and b are both Google Map GPoints
                                                    */
function point_distance(a, b) {
  var r = 6378700;
  var lat1 = a.y;
  var lat2 = b.y;
  var lon1 = a.x;
  var lon2 = b.x;
  var dist = r * Math.acos(Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + 
			   Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
			   Math.cos(deg2rad(lon1 - lon2)));
  return dist;
}

/* Calculate the approximate distance to the edge of 
   the viewable map in miles. This assumes that the 
   viewable area is square-like in shape.            */


 function getXml(url,catsToDisplay, markersToDisplay, useSidebar) {
    var request = GXmlHttp.create();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
     if (request.readyState == 4) {
        try {
            var xmlDoc = request.responseXML;
        } catch(err) {
            var data = request.responseText;
            var xmlDoc = GXml.parse(data);
        }
        infoWindows = xmlDoc.getElementsByTagName("info");
        xmlCats = xmlDoc.getElementsByTagName("category");
        var catset = 0;
        for (var j = 0; j < infoWindows.length ; j++) {
          // Grab variables about the type of marker.
          var pid = infoWindows[j].getAttribute("id");
          var ptype = infoWindows[j].getAttribute("type");
          var pcat = infoWindows[j].getAttribute("category");
          if(checkCat(pcat,catsToDisplay) && checkCat(pid, markersToDisplay)) {
            // Checking to see if the info is for a polyline or a marker
            if( ptype == 2 ) {
                // Code for a polyline
                // get any line attributes
                var misc = infoWindows[j].getElementsByTagName("misc");
                var color = misc[0].getAttribute("polycolor");
                var width  = parseFloat(misc[0].getAttribute("polywidth"));
                // read each point on that line
                var points = infoWindows[j].getElementsByTagName("point");
                var pts = [];
                for (var i = 0; i < points.length; i++) {
                    pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
                                         parseFloat(points[i].getAttribute("lng")));
                }
                map.addOverlay(new GPolyline(pts,color,width));
              } else {
                // Code for a marker
//                var markerObj = new createMarker2(infoWindows[j],j);
//                newmarkers.push(markerObj);
                markers[j] = createMarker(infoWindows[j],j);
				
				
                // This opens the info window if automatic open is set on.
                if(centerId == pid && autoOpen == 1) {
                    if(safariCompat == 1) {
                        var html = infoHtml(infoWindows[j]);
                    } else {
                        var html = xsltProcess(infoWindows[j], xmlHttp.responseXML);
                    }
                    markers[j].openInfoWindowHtml(html);
                }
              }
          }
        }
		//mm.addMarkers(markers, 8,15);

        // Envokes the function to create the sidebar.
        if(useSidebar == 1) {
		    try {
			    showItems(sidebar_num,sidebar_place);
		    } catch(err){}
        }
     }
    }
  request.send(null);
 }
 
 
 // This function opens/closes/changes the various map comtrols
 function mapOptions(type, scale, zoom) {
   // This shows or hides the map type buttons (normal, sat, hybrid).
   switch(type) {
	case 1:
		map.addControl(new GMapTypeControl());
		break;
	default:
		break;
   }
   // This switches the scale on or off.
   switch(scale) {
	case 1:
		map.addControl(new GScaleControl());
		break;
	default:
		break;
   }
   // This chooses which zoom/pan control to use. There are 3 
   // choices and the ability to hide the control all together
   switch(zoom) {
	case 1:
		map.addControl(new GLargeMapControl());
		break;
	case 2:
		map.addControl(new GSmallMapControl());
		break;
	case 3:
		map.addControl(new GSmallZoomControl());
		break;
	default:
		break;
   }

 }

 // Grabs the current api version number 
 var APIkey = "";
 function getGoogleMapsVersion() {
	var i, a, b, c;
	var v = "unknown";

	if (document.getElementsByTagName)
		for(i=0; (a = document.getElementsByTagName("script")[i]); i++)
			if(a.getAttribute("src"))
			{
				b = a.getAttribute("src");
				c = b.indexOf("/mapfiles/maps");
				d = b.indexOf("http://maps.google.com/maps?file=api");
				e = b.indexOf("key=");
				if (c > 0)
					v = parseFloat(b.substring(c+14));
				if (d >= 0)
					if (e > 0)
						APIkey = b.substring(e+4);
			}
	return v;
 }
 
 // Enable a couple zoom options.
 function zoomOptions(continuous, doubleclick) {
    if(continuous == 1) {
        map.enableContinuousZoom();
    }
    if(doubleclick == 1) {
        map.enableDoubleClickZoom();
    }
 }
 
 // Controls the overview (mini) map
 function initOverview(show,width,height) {
       if(show != 0) {
             //  ======== Add a map overview ==========
             map.addControl(new GOverviewMapControl(new GSize(width,height)));
             if(show == 2) {
                  setTimeout("positionOverview(520,580)",1);
             } else if(show == 1) {
                  omap = document.getElementById("map_overview"); 
                  document.getElementById("map").appendChild(omap);
             }
       }
 } 
 
 // This function loads the map, but only after the page has loaded.      
 function initMap() {
  // Checks to see if the browser is compatible with Google Maps API
  if(GBrowserIsCompatible) {
   // Not quite sure why this is here.
   i = 0;
   // Initialize the map
   map = new GMap2(document.getElementById("map"));
   // Now to show all the various widgets on the map
   mapOptions(showType,showScale,whichZoom);
   // Here we set the center of the map and the map type
   map.setCenter(new GLatLng(centerLat,centerLng),zoomLevel,whichType);   
   // Enable zoom options
   zoomOptions(contZoom, doubleclickZoom);
   
   //mm = new GMarkerManager(map, {maxZoom: 15}); 

   // This gets the marker data and plots the points to the map
   getXml(xmlUrl, catDisplay, pointsArray, sidebar_exists);
   // If tooltips are enabled then this sets up the tooltips
  
   // Add listener to the map
   GEvent.addListener(map, "zoomend",  function updateTable(){
        sidebar_html = "";
        //sidebar_html = data_html + header_html;
        var bounds = map.getBounds();
        var SW = bounds.getSouthWest();
        var NE = bounds.getNorthEast();
        var NElat = NE.lat();
        var NElng = NE.lng();
        var SWlat = SW.lat();
        var SWlng = SW.lng();
        //fix for international date line
        if (SWlng > 100) SWlng = -180;
        //alert ("SW lat: " + SWlat + " lng: " + SWlng);
		//alert(markers[]);
		current_sidebar = "<table border='0' width='100%' >";
		for (var j = 0; j < markers.length; j++){
                var point = markers[j].getPoint();
                if ((point.lat() < NElat) && (point.lat() > SWlat)){
                        if ((point.lng() < NElng) && (point.lng() > SWlng)){
                                // Envokes the function to create the sidebar.
								 //markers[j] = createMarker(infoWindows[j],j);
								info = infoWindows[j];
								var localId = info.getAttribute("id");
								var localType = info.getAttribute("type");
								var localName = GXml.value(info.getElementsByTagName("ref")[0]);
								var localPrice = GXml.value(info.getElementsByTagName("price")[0]);
								var localCur_from = GXml.value(info.getElementsByTagName("cur_from")[0]);
								var localCity = GXml.value(info.getElementsByTagName("city")[0]);
								var localCountry = GXml.value(info.getElementsByTagName("country")[0]);
								var localCatid = info.getAttribute("category");
								var localDrag = info.getAttribute("draggable");
								var localLat = info.getAttribute("lat");
								var localLng = info.getAttribute("lng");
								current_sidebar +=  "<tr style='cursor:pointer;' bgcolor='#CCCCCC' ><td width='5%'>" + i +"</td>"+ "<td width='30%'><a href='javascript:myclick("+j+"," + localLng + "," + localLat +",15)' onmouseover='tooltipMouseover("+j+")' onmouseout='tooltipMouseout()'> " + localCity + "</a></td><td width='30%'>" + localCountry + "</td><td width='30%'>" + localPrice + "</td><td width='30%'>" + localName + "</td><td>" + localCur_from+ "</td></tr>";
                        }
                }
        }
		current_sidebar += "</table>";
		document.getElementById("google_maps_sidebar").innerHTML = current_sidebar;
} );
     
   initTooltip(tooltipShow);
   // If the overview map is enabled then it is envoked here.
   initOverview(overviewShow,overviewWidth,overviewHeight);
   //mm.refresh();
   
  } else {
    alert("Your browser is not compatible with the Google Maps API");
  }
 }
