var gdir_image_count = 0;

function GMapLoad(direction_sw)
{
        // latitude, longitude, company_name, addr_street, addr_city_state, 
        // advertiser_latitude, advertiser_longitude, advertiser_name, advertiser_addr_street, advertiser_addr_city_state variables
        // are set by the calling page
        
        if(typeof(latit_longit_accuracy) !="undefined")
        {
                if(latit_longit_accuracy == '0')
                {
                        document.getElementById('gmap').innerHTML+= ' no map available';
                        return;
                }
        }

        if (GBrowserIsCompatible())
        {
            
          var map = new GMap2(document.getElementById("gmap"));
	  var geocoder= new GClientGeocoder();
	  var orig_latlng= new GLatLng(latitude, longitude);
	  var latlng= new GLatLng(latitude, longitude);
	  geocoder.getLatLng(addr_street + ' ' + company_zipcode, function(ll){
			if(ll != null) {
				latlng= ll;
			}
			else {
				latlng= orig_latlng;
			}
			GMapLoadAgain(direction_sw, map, latlng, orig_latlng);
		}
	  );
	}
}

function GMapLoadAgain(direction_sw, map, latlng, orig_latlng) {
          map.setCenter(latlng, 12);
          map.addControl(new GLargeMapControl());
          map.addControl(new GMapTypeControl());
          
       if (direction_sw) {
	    var adv_index=direction_sw-1;
            var directionsPanel;
            directionsPanel = document.getElementById("gdirection");
            gdir = new GDirections(map, directionsPanel);
            gdir.clear();
            directionsPanel.innerHTML = '';
            error_dir_sw = direction_sw; // For error.
	    gdir.load("from: "+latitude+","+longitude+" to: "+nearest_advertisers[adv_index].latitude+","+nearest_advertisers[adv_index].longitude, {"preserveViewport": false });

	    //hide my direction link amd show others
	    for(var i=1; i<=nearest_advertisers.length; i++) {
		if(i == direction_sw) {
			document.getElementById("directionlink"+i).style.display = 'none';
		}
		else {
			document.getElementById("directionlink"+i).style.display = 'block';
		}
	    }
	    document.getElementById("hidedirectionlink").style.display = 'block';
	    //

	    GEvent.addListener(gdir, "error", handleErrors);
	    gdir_holder= gdir;
            nearest_advertiser = nearest_advertisers[adv_index];
	    GEvent.addListener(gdir, "load", replaceMapMarkers);
	    GEvent.addListener(gdir, "addoverlay", replaceDirMarkers);
      
	}
	else {
	    var point = latlng;
            var infowindow = "<b>" + company_name + "</b><br>" + addr_street + "<br>" + addr_city_state+"<br>Phone: "+phone+"<br><a href='"+profile_link+"'>company profile</a> | <a href='"+cbi_link+"'>reports &amp; articles</a>";
            map.addOverlay(createMarker(point,"http://www.manta.com/manta/images/favicon.gif",infowindow));

	    AddAdvertiserMarkers(map);  // function in the html page for dynamic result
            directionsPanel = document.getElementById("gdirection");
            for(var i=1; i<=nearest_advertisers.length; i++) {
		document.getElementById("directionlink"+i).style.display = 'block';
	    }
            document.getElementById("hidedirectionlink").style.display = 'none';
	    directionsPanel.innerHTML = '';

//		var panoClient = new GStreetviewClient();
//		panoClient.getNearestPanoramaLatLng(latlng, function(glatlong){
//			var panoDiv = document.getElementById('gstreetview');
//			var pano = new GStreetviewPanorama(panoDiv);
//			GEvent.addListener(pano, 'error', function(errorCode) {
//					if (errorCode == 603) {
//						panoDiv.innerHTML = 'StreetView requires flash plugin. Click <a href="http://get.adobe.com/flashplayer/" target="_blank"> here</a> to download';
//					}
//	                });
//			if (glatlong) {
//				pano.setLocationAndPOV(glatlong);
//                	}
//			else {
//				pano.setLocationAndPOV(orig_latlng);
//			}
//		});
//		var mads_opts= {maxAdsOnMap: 5};
//		var mads= new GAdsManager(map,  'pub-5318756859004963', mads_opts);
//		mads.enable();
	}
}

function replaceMapMarkers()
{
    var icon= gdir.getMarker(1).getIcon();
    
    icon.image= nearest_advertiser.marker;
    icon.shadow = "http://www.manta.com/manta/images/shadow.png";
    icon.iconSize = new GSize(nearest_advertiser.marker_w, nearest_advertiser.marker_h);
    icon.shadowSize = new GSize(37, 34);

	icon= gdir.getMarker(0).getIcon();
	icon.image= 'http://www.manta.com/manta/images/favicon.gif';
	icon.shadow = "http://www.manta.com/manta/images/shadow.png";
	icon.iconSize = new GSize(30, 30);
	icon.shadowSize = new GSize(37, 34);
}
function replaceDirMarkers()
{

    var directionsPanel = document.getElementById('gdirection');

    gdir_image_count = 0;
    ReplaceDirectionIcons(directionsPanel);
}


function createIcon(icon_image,w,h)
{
  var icon = new GIcon();
  icon.image = icon_image;
  icon.shadow = "http://www.manta.com/manta/images/shadow.png";
  icon.iconSize = new GSize(26,26);
  if (w && h) {
	icon.iconSize = new GSize(w, h);
  }

  icon.shadowSize = new GSize(37, 34);
  icon.iconAnchor = new GPoint(9, 34);
  icon.infoWindowAnchor = new GPoint(9, 2);
  icon.infoShadowAnchor = new GPoint(18, 25);
  return icon;
}

function createMarker(point, icon_image, infowindow,w,h)
{
  var icon= createIcon(icon_image,w,h);

  var marker = new GMarker(point, { icon:icon, zIndexProcess:ImportanceOrder });
  
  if (icon_image == "http://www.manta.com/manta/images/favicon.gif")
  {
  
        marker.importance = 1;
  
  }
  else // Advertisers
  {
  
    marker.importance = 2;
  
  }
  
  GEvent.addListener(marker, "mouseover", function() {
    marker.openInfoWindowHtml(infowindow);
  });
  return marker;
}

function handleErrors()
{
  if(try_direct_by_latlon)
  {
	  try_direct_by_latlon_now=1;
	  GMapLoad(error_dir_sw);
  }
  else
  {
  	document.getElementById("gdirection").innerHTML = '<br><strong>Sorry, no directions are available.</strong>';
  }
  try_direct_by_latlon= 0;
}

function ImportanceOrder(marker, b)
{
    return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance * 1000000;
}
function fixSrc(img,src) {if(img.src != src){img.src=src}}
function ReplaceDirectionIcons(element)
{
    
    if (element.tagName == 'IMG')
    {
        gdir_image_count++;
        
        if (gdir_image_count == 1) {
		element.setAttribute("src", "http://www.manta.com/manta/images/favicon.gif");
		element.setAttribute("onload", "fixSrc(this,'http://www.manta.com/manta/images/favicon.gif')");
            //element.width = 26;element.height = 26; //scale it up to 26x26
            element.hspace = 4;
            element.vspace = 2;
        }
	else if (gdir_image_count == 2) {
		element.setAttribute("src", nearest_advertiser.marker);
		element.setAttribute("onload", "fixSrc(this,nearest_advertiser.marker)");
            element.hspace = 4;
            element.vspace = 2;
        
        }
    }

    for (var i = 0; i < element.childNodes.length; i++) {
        ReplaceDirectionIcons(element.childNodes[i]);
    }

}

function ReplaceDirectionIconsNow(element)
{
    
    if (element.tagName == 'IMG')
    {
   
        gdir_image_count++;
        element.src = element.src_temp;
    
    }

    for (var i = 0; i < element.childNodes.length; i++)
    {
    
        ReplaceDirectionIcons(element.childNodes[i]);
    
    }

}

function DoTheImageReplace()
{

    var directionsPanel = document.getElementById('gdirection');
    ReplaceDirectionIcons(directionsPanel);
    console.debug("DoTheImageReplace()");

}

function GrabDirectionsHTML()
{

    

}
