
function AddClass(obj,cName){ KillClass(obj,cName); return obj && (obj.className+=(obj.className.length>0?' ':'')+cName); }
function KillClass(obj,cName){ return obj && (obj.className=obj.className.replace(new RegExp("^"+cName+"\\b\\s*|\\s*\\b"+cName+"\\b",'g'),'')); }
function HasClass(obj,cName){ return (!obj || !obj.className)?false:(new RegExp("\\b"+cName+"\\b")).test(obj.className) }
function GetWindowWidth(){var width=0;if(typeof(window.innerWidth)=='number'){width=window.innerWidth;}else if(document.documentElement&&document.documentElement.clientWidth){width=document.documentElement.clientWidth;}else if(document.body&&document.body.clientWidth){width=document.body.clientWidth;}if(!width||width<100){width=100;}return width;}
function GetWindowHeight(){var height=0;if(typeof(window.innerHeight)=='number'){height=window.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){height=document.documentElement.clientHeight;}else if(document.body&&document.body.clientHeight){height=document.body.clientHeight;}if(!height||height<100){height=100;}return height;}
	/**  These types will be used to change maps type */
	var MAP_TYPE_REG = 0;
	var MAP_TYPE_SAT = 1;
	var MAP_TYPE_HYB = 2;
	var GoogleMapTypes = new Array(3);
	GoogleMapTypes[MAP_TYPE_REG] = G_NORMAL_MAP;
	GoogleMapTypes[MAP_TYPE_SAT] = G_SATELLITE_MAP;
	GoogleMapTypes[MAP_TYPE_HYB] = G_HYBRID_MAP;

	var GoogleMapTypesReverse = new Array(3);
	GoogleMapTypesReverse[G_NORMAL_MAP.getName()] = MAP_TYPE_REG;
	GoogleMapTypesReverse[G_SATELLITE_MAP.getName()] = MAP_TYPE_SAT;
	GoogleMapTypesReverse[G_HYBRID_MAP.getName()] = MAP_TYPE_HYB;

	var YahooMapTypes = new Array(3);
	YahooMapTypes[MAP_TYPE_REG] = YAHOO_MAP_REG;
	YahooMapTypes[MAP_TYPE_SAT] = YAHOO_MAP_SAT;
	YahooMapTypes[MAP_TYPE_HYB] = YAHOO_MAP_HYB;

	var YahooMapTypesReverse = new Array(3);
	YahooMapTypesReverse[YAHOO_MAP_REG] = MAP_TYPE_REG;
	YahooMapTypesReverse[YAHOO_MAP_SAT] = MAP_TYPE_SAT;
	YahooMapTypesReverse[YAHOO_MAP_HYB] = MAP_TYPE_HYB;

var trackLatitude  = false;
	var qs = new Querystring(null);
	var lat, lon;
	var INITIAL_ZOOM_LEVEL;
    var CURRENT_LAT_POSITION;
    var CURRENT_LON_POSITION;
    var CURRENT_MAP_TYPE2;    
    var CURRENT_ZOOM_LEVEL;
    var CURRENT_YZOOM_LEVEL;
    var MAPLEADER;
	var current_gmap_control;
	var container;
	var g_geocoder = new GClientGeocoder();
	var geo = new GClientGeocoder(new GGeocodeCache()); 
    var gdir;
	var bounds;    
    var addressMarker;
    var searchmode;
      var poly;
     /** check the visibility of maps*/ 		
	var GGVisible= true;
	var YYVisible= true;
	var VEVisible= true;	
    var MiniMapSize = VEMiniMapSize.Small; // can also be set to VEMiniMapSize.Large       
          var confidenceStrings = ["High", "Medium", "Low"];
         var precisionStrings  = ["Interpolated", "Rooftop"];
 
         var pushpinUrls       = ["pushpinGreen.gif", "pushpinOrange.gif", "pushpinRed.gif"];     

if (qs.get("lat") != null) {
		lat = qs.get("lat");
		lon = qs.get("lng");
	} else {		
		var lat = 0;
		var lon = 0;
	}
      
	if (qs.get("z") != null) {
		INITIAL_ZOOM_LEVEL = qs.get("z");
	} else {
		INITIAL_ZOOM_LEVEL =6;
	}
      
      
      
	var ve_map = null;
	var g_map = null;
	var map = null;
    var ov_map = null;  
	var init_width, init_height;
		var txtFrom; 
		var txtTo;



	  var minimap = null;
	/**  var minizoomlevel = null;*/
	  var pinid = 0;



	var CURRENT_MAP_TYPE = MAP_TYPE_REG;




	function load(address)
	{

		try
    	{ 
    	    MAPLEADER ='VE';
           if (lat == 0) {lat = document.getElementById("hidLat").value;}
           if (lon == 0) {lon = document.getElementById("hidLon").value;}
			setZoomLevelConstant(INITIAL_ZOOM_LEVEL);
			GoogleGeocoder = new GClientGeocoder();
			init(lat, lon, INITIAL_ZOOM_LEVEL, CURRENT_MAP_TYPE);
			UpdateStatusforPosition(lat,lon);

		//	document.getElementById("searchdirectId").className='activetitlink';

	}   catch(err)
    	{
        	/**alert("Error in load!",err.message); */
    	}
	}

	function init(lat, lng, zoom, type)
	{
	    try
	    {
		    CURRENT_MAP_TYPE = type;
		    if(GGVisible)
		    drawGM(lat, lng, zoom, type);
		    if(YYVisible)		    
		    loadYahoo(lat, lng, zoom, type);
		    if(VEVisible)		    
		    drawVE(lat, lng, zoom, type);

		    UpdateStatusforPosition(lat,lng);
		      SizeDivs();
		      showRouteSearch();
            g_map.setCenter(new GLatLng(lat, lng), GoogleZoomLevel(zoom));		

	    }   catch(err)
        {
            /**alert("Error! in init",err.message);  */
        }
        

	}

	function MarkOnMap(lat, lon, city,countryCode,countryName,region)
	{
	var title= document.getElementById("txtIPSearch").value + "  " + city;
	
	               /**  create the info box description */
               var desc = "Latitude: " + lat + "<br/>" +
                          "Longitude: " + lon;
               desc = desc + "<br>Country Name: " + countryName;
               desc = desc + "<br>Country Code: " + countryCode;
               desc = desc + "<br>Region: " + region;
            v_zoom=10;
            SetLocation(lat,lon,v_zoom,title, desc);
	}

	function SetLocation(v_lat, v_lon, v_zoom,title, desc)
	{
	    try
	    {

		   if(VEVisible)	
		    {	    
		        ve_map.SetCenterAndZoom(new VELatLong(v_lat,v_lon),MMZoomLevel(v_zoom));   
		        createMarkerOnVE(v_lat,v_lon,0,title,desc,0)
     	    } 
		    if(GGVisible)
		    {
		        g_map.setCenter(new GLatLng(v_lat, v_lon), GoogleZoomLevel(v_zoom));
    			g_map.addOverlay(createNonDragableMarkeronGMap(new GLatLng(v_lat, v_lon), 0, title + '<br/>' + desc));		        
		    }
		    if(YYVisible)		 
		    {   
		        YahooMap.panToLatLon(new YGeoPoint(v_lat, v_lon));
		        YahooMap.setZoomLevel(YahooZoomLevel(v_zoom))
		        var currentGeoPoint = new YGeoPoint(v_lat, v_lon);
				CreateMarkerOnYMap(currentGeoPoint,title + '<br/>' + desc);
		     }

             UpdateStatusforPosition(v_lat,v_lon);
	    }   

	    catch(err)
        {
            /**alert("Error! in init",err.message);  */
        }

	}
	function GotoLocation(v_lat, v_lon, v_zoom)
	{
	    try
	    {

		   if(VEVisible)	
		    {	    
		        ve_map.SetCenterAndZoom(new VELatLong(v_lat,v_lon),MMZoomLevel(v_zoom));   
     	    } 
		    if(GGVisible)
		    {
		        g_map.setCenter(new GLatLng(v_lat, v_lon), GoogleZoomLevel(v_zoom));
		    }
		    if(YYVisible)		 
		    {   
		        YahooMap.panToLatLon(new YGeoPoint(v_lat, v_lon));
                YahooMap.setZoomLevel(YahooZoomLevel(v_zoom))		        
		     }

              UpdateStatusforPosition(v_lat,v_lon);
	    }   

	    catch(err)
        {
            /**alert("Error! in init",err.message);  */
        }

	}	

	
  /** Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/

function Querystring(qs) { 
	try
	{
	this.params = new Object();
	this.get=Querystring_get;
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length);

	if (qs.length == 0) return;

/** Turn <plus> back to <space>*/
/** See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1*/
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); /** parse out name/value pairs separated via &*/
	
/** split out each name=value pair */
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=');
		var name = unescape(pair[0]);

		if (pair.length == 2)
			value = unescape(pair[1]);
		else
			value = name;
		
		this.params[name] = value;
	}
	}   catch(err)
    {
        /**alert("Error!Querystring",err.message); */
    }

}

function Querystring_get(key, default_) {
	try
	{
	/** This silly looking line changes UNDEFINED to NULL*/
	if (default_ == null) default_ = null;
	
	var value=this.params[key];
	if (value==null) value=default_;
	
	return value;

	}   catch(err)
    {
        /**alert("Error!Querystring_get",err.message); */
    }
	
}

    function debug(message) 
    {
    	/**GLog.write(message);*/
    }
      
    function updateVEMapsMoveAndZoom(v_lat, v_lon, v_zoom)
    {
        if (MAPLEADER != 'VE')
        return; 
    	try
	{

    

    		v_lat = ve_map.GetCenter().Latitude;
    		v_lon = ve_map.GetCenter().Longitude;
    		v_zoom = ve_map.GetZoomLevel();
    	setZoomLevelConstant(YahooZoomLevel(v_zoom));
		if(GGVisible)
		g_map.setCenter(new GLatLng(v_lat, v_lon), GoogleZoomLevel(v_zoom));
		
        if(YYVisible)
        {
            YahooMap.panToLatLon(new YGeoPoint(v_lat, v_lon));
            YahooMap.setZoomLevel(YahooZoomLevel(v_zoom))
        }	
		
		UpdateStatusforPosition(v_lat,v_lon);

	}   catch(err)
    {
    /**alert("Error!updateGMap",err.message); */
    }
    	
 }

    function updateGoogleMapsMoveAndZoom()
    {
        if (MAPLEADER != 'GG')
        return; 
    	try
	{

		var v_lat, v_lon, v_zoom;
    		v_lat = g_map.getCenter().lat();
    		v_lon = g_map.getCenter().lng();
    		v_zoom = g_map.getZoom();
		     setZoomLevelConstant(YahooZoomLevel(v_zoom));    		
			
			if(VEVisible)
			{
			ve_map.SetCenterAndZoom(new VELatLong(v_lat,v_lon),MMZoomLevel(v_zoom));	
			
			/**DrawMiniMap();*/
			}
			if(YYVisible)
			{
			YahooMap.panToLatLon(new YGeoPoint(v_lat, v_lon));
			YahooMap.setZoomLevel(YahooZoomLevel(v_zoom))
			}
		    UpdateStatusforPosition(v_lat,v_lon);
	}   catch(err)
    {
	/**alert("Error!updateMMap",err.message); */
    }
    	
    }
    
    
  
    
    
    
	function updateYMapsMoveAndZoom()
	{
	    if (MAPLEADER != 'YY')
        return; 
	try
	{	
		var v_lat, v_lon, v_zoom;
		var y = YahooMap.getCenterLatLon();
		v_lat = y.Lat;
		v_lon = y.Lon;
		v_zoom = YahooZoomLevel(YahooMap.getZoomLevel());
		setZoomLevelConstant(v_zoom);

		if(GGVisible)		
		g_map.setCenter(new GLatLng(v_lat, v_lon), GoogleZoomLevel(v_zoom));

	    if(VEVisible)
	    ve_map.SetCenterAndZoom(new VELatLong(v_lat,v_lon),MMZoomLevel(v_zoom));	

		   UpdateStatusforPosition(v_lat,v_lon);

	}   catch(err)
    {
     /**alert("Error!updateYMapsMoveAndZoom",err.message); */
    }

}

function updateVMapZoom()
{
    
    if (MAPLEADER != 'VE')
        return; 
    
        
	try
	{	
	var zoomlevel;
	zoomlevel =  ve_map.GetZoomLevel();
    setZoomLevelConstant(YahooZoomLevel(zoomlevel));
	if(YYVisible)
	{
	YahooMap.setZoomLevel(YahooZoomLevel(zoomlevel))
	}
	if(GGVisible)		
 	g_map.setZoom(GoogleZoomLevel(zoomlevel));
 	UpdateStatusforZoom(zoomlevel);

 	/**	if(VEVisible)		
    DrawMiniMap();*/
	
    }   catch(err)
    {
        /**alert("Error!updateGMapZoom",err.message); */
    }
}

	


	function updateYahooZoom()
	{
        if (MAPLEADER != 'YY')
        return; 	
		var level =  YahooZoomLevel(YahooMap.getZoomLevel());
        setZoomLevelConstant(level);
	    try
	    {	

	        if(GGVisible)
		    g_map.setZoom(GoogleZoomLevel(level));
		    if(VEVisible)
    		 ve_map.SetZoomLevel(MMZoomLevel(level)); 
    		 
 	        UpdateStatusforZoom(MMZoomLevel(level));
	    }   catch(err)
        {
            /**alert("Error!setZoomLevel",err.message); */
        }	
	}


	function getZoomLevel()
	{
		return CURRENT_YZOOM_LEVEL;
	}

	function setZoomLevelConstant(Yahoolevel )
	{
		CURRENT_YZOOM_LEVEL = Yahoolevel;
	}


	function GoogleZoomLevel(level)
	{
		return level;
	}

	function MMZoomLevel(level)
	{
		return level;
	}	
	
	function YahooZoomLevel(level)
	{
		return 18 - level;
	}

function setOwner(Owner)
{

MAPLEADER = Owner;
}

    function drawVE(lat, lng, zoom, type) {
	try
	{    

		  ve_map = new VEMap('ve');
		 ve_map.LoadMap();
		
		 /**minimap = new VEMap('myMiniMap');
		 minimap.LoadMap(null,null,'h');*/
		 /** minizoomlevel = zoom;	 
		DrawMiniMap();*/
		  ve_map.ShowMiniMap(0,0,MiniMapSize); 
		/** minimap.HideDashboard();
		minimap.SetMapStyle('r');*/
        ve_map.AttachEvent("onendcontinuouspan", updateVEMapsMoveAndZoom);
        ve_map.AttachEvent("onendzoom", updateVMapZoom);
        ve_map.AttachEvent("onchangemapstyle", UpdateVEMapsType);
        ve_map.AttachEvent("onmouseup", updateVEMapsMoveAndZoom);
        ve_map.AttachEvent("oncontextmenu", popupmenuforVE);
        ve_map.AttachEvent("onclick", popupmenuforVE);

        ve_map.SetCenterAndZoom(new VELatLong(lat,lon),MMZoomLevel(zoom));	



	/**	 minimap.AttachEvent("onmousedown", DisableMiniMap);
		 minimap.AttachEvent("ondoubleclick", DisableMiniMap);
		 minimap.SetMapStyle('r');*/

	}   catch(err)
    {
        /**alert("Error!drawVE",err.message); */
    }
		 
}
	
	function drawGM(lat, lng, zoom, type) {
	try
	{
	
		debug("Drawing GM with zoom of " + INITIAL_ZOOM_LEVEL);
		
	if (GBrowserIsCompatible())
	 {
	container = document.getElementById("ggl");

	    g_map = new GMap2(container, {draggableCursor:"crosshair"});
	    g_map.addControl(new GMapTypeControl());
	    g_map.addControl(new GScaleControl());
	    g_map.addControl(new GLargeMapControl()); 
		g_map.enableDoubleClickZoom(); 
		g_map.enableContinuousZoom();
		g_map.enableScrollWheelZoom();
		 bounds = new GLatLngBounds();
			    
		
		
        g_map.setMapType(GoogleMapTypes[type]);
		GEvent.addListener(g_map, "moveend",updateGoogleMapsMoveAndZoom);
/**		GEvent.addListener(g_map, "zoomend", updateGoogleMapsZoom); */
		
        GEvent.addListener(g_map, 'maptypechanged', UpdateGMapsType);		
			
		
		gdir = new GDirections(g_map, document.getElementById("ZdDlgtext"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        
        
        
        
        
        GEvent.addListener(gdir, "error", handleErrors);
        GEvent.addListener(g_map, "singlerightclick", ShowPopupMenuForGMAP);
        GEvent.addListener(g_map, "click", RemovePopMenuForGMAP);

		var ovcontrol = new GOverviewMapControl(new GSize(130	,130));
		g_map.addControl(ovcontrol);
		ov_map = ovcontrol.getOverviewMap();
	    g_map.setCenter(new GLatLng(lat, lng), GoogleZoomLevel(zoom));		



		}

	}   catch(err)
    {
        /**alert("Error!drawGM",err.message); */
    }
		
}	    	  
	
	var YahooMap;

	function loadYahoo(lat, lng, zoom, type)
	{
	try
	{	
		YahooMap = new YMap(document.getElementById('YahooMap'));
		YahooMap.setMapType(YahooMapTypes[type]);
		YahooMap.drawZoomAndCenter(new YGeoPoint(lat, lng), YahooZoomLevel(zoom));
		YahooMap.addTypeControl();
		YahooMap.addZoomLong();
		YahooMap.addPanControl();
		YEvent.Capture(YahooMap, EventsList.endPan, updateYMapsMoveAndZoom);
		YEvent.Capture(YahooMap, EventsList.changeZoom, updateYahooZoom);
		YEvent.Capture(YahooMap, EventsList.endMapDraw, updateYMapsType);
		YEvent.Capture(YahooMap, EventsList.MouseClick, ShowPopupMenuForYMAP);
		/**YEvent.Capture(YahooMap, EventsList.changeZoom, GoogleSyncMapTypeWithYahoo);
		 		YEvent.Capture(YahooMap, EventsList.endAutoPan , GoogleSyncMapTypeWithYahoo);*/

	}   catch(err)
    {
        /**alert("Error!loadYahoo",err.message); */
    }
		
 }	
	




	function UpdateVEMapsType(e) {
	
        if (MAPLEADER != 'VE')
        return; 	
	try
	{	
		var type = ve_map.GetMapStyle();
		if(GGVisible)
		{
		    if (type == VEMapStyle.Hybrid) {
			    g_map.setMapType(G_HYBRID_MAP);
		    } else if (type == VEMapStyle.Road) {
			    g_map.setMapType(G_NORMAL_MAP);
		    } else if (type == VEMapStyle.Aerial) {
			    g_map.setMapType(G_SATELLITE_MAP);
		    } else {
		    }
    		

    		
	        var google_type = g_map.getCurrentMapType().getName();

		    CURRENT_MAP_TYPE = YahooMapTypes[GoogleMapTypesReverse[google_type]];
		      }
		     if(YYVisible)
		        YahooMap.setMapType(YahooMapTypes[GoogleMapTypesReverse[google_type]]);	
    		
		    if(VEVisible)
		    {
		    /**have to check if you entered birds eye style on the main map*/
		    if(e.mapStyle == "o")
		    {
		    /**minizoomlevel = 3;*/
		    }
		    /**if we change style of main map to anything else, reset the zoom level for mini-map*/
		    else
		    {
/**				    minizoomlevel = ve_map.GetZoomLevel();
			    DrawMiniMap();*/
		    }
	    }
	}   
	catch(err)
    {
     /**alert("Error!changeGMapType",err.message);*/ 
    }
	
}

	function updateYMapsType()
	{
        if (MAPLEADER != 'YY')
        return; 
		try
		{	
			var yahoo_type = YahooMap.getCurrentMapType();

			CURRENT_MAP_TYPE = YahooMapTypesReverse[yahoo_type];
            if(GGVisible)		
			g_map.setMapType(GoogleMapTypes[YahooMapTypesReverse[yahoo_type]]);
	        if (VEVisible)
	        {
			    var type = g_map.getCurrentMapType();
			    if (type == G_HYBRID_MAP) {
				    ve_map.SetMapStyle('h');
			    } else if (type == G_NORMAL_MAP) {
				    ve_map.SetMapStyle('r');
			    } else if (type == G_SATELLITE_MAP) {
				    ve_map.SetMapStyle('a');
			    } else {
			    }		
		    }
			UpdateStatusforMapType(yahoo_type)

		}   catch(err)
		{
			        /**alert("Error!GoogleSyncMapTypeWithYahoo",err.message); */
		}	
	}	
	
		function UpdateGMapsType(e)
{
        if (MAPLEADER != 'GG')
        return; 
	try
	{
	
		var google_type = g_map.getCurrentMapType().getName();

		CURRENT_MAP_TYPE = GoogleMapTypesReverse[google_type];
        if(YYVisible)		
		YahooMap.setMapType(YahooMapTypes[GoogleMapTypesReverse[google_type]]);

        try {ov_map.setMapType(G_NORMAL_MAP);}catch(err){}
	    if (VEVisible)
	    {
			var type = g_map.getCurrentMapType();
			if (type == G_HYBRID_MAP) {
				ve_map.SetMapStyle('h');
			} else if (type == G_NORMAL_MAP) {
				ve_map.SetMapStyle('r');
			} else if (type == G_SATELLITE_MAP) {
				ve_map.SetMapStyle('a');
			} else {
			}		
		}
				/**minizoomlevel = ve_map.GetZoomLevel();
				if(VEVisible)		
				DrawMiniMap();*/
        UpdateStatusforMapType(YahooMapTypes[GoogleMapTypesReverse[google_type]])

	}   catch(err)
    {
        /**alert("Error!SyncMapTypeWithGoogle",err.message); */
    }				

}	
		function changeMapTypes(type)
{
	try
	{
	
		CURRENT_MAP_TYPE = type;
        if(YYVisible)		
		YahooMap.setMapType(YahooMapTypes[type]);
		if(GGVisible)		
		g_map.setMapType(GoogleMapTypes[type]);

        UpdateStatusforMapType(YahooMapTypes[type])


	}   catch(err)
    {
        /**alert("Error!changeMapTypes",err.message); */
    }
		
}
	
	function drawPopupMenu()
	{
	try
	{	
			navRoot = document.getElementById("popupmenu");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
					KillClass(this, 'right');
					KillClass(this, 'left');
					this.className+= " " + side;
				};
				node.onmouseout=function() {
					KillClass(this, 'over');
				};
			}
		}

	}   catch(err)
    {
        /**alert("Error!drawPopupMenu",err.message); */
    }
	
}

function getMapCount()
{
	 	var mapcount =0;
	    if (GGVisible)
	    mapcount = mapcount + 1;
		if (YYVisible)
	    mapcount = mapcount + 1;   
	    if (VEVisible)
	    mapcount = mapcount + 1;  
	    return mapcount;
}
	function SizeDivs() {
	

    try
    {	
	    var mapcount =getMapCount();
 
	    if (mapcount ==3 || mapcount ==2)
	    {
        init_width = Math.floor((document.body.clientWidth -5 ) / 2);
	    init_height = Math.floor(document.body.clientHeight ) / 2;
	    }
	    
	   if (mapcount ==1)
	    {
        init_width = Math.floor(document.body.clientWidth - 5);
	    init_height = Math.floor(document.body.clientHeight );
	    }
	    


        if (GGVisible)
        {

            document.getElementById('ggMap').style.width = init_width + "px";
            document.getElementById('ggMap').style.height = init_height + "px";
            document.getElementById('ggl').style.width = init_width + "px";
    	    document.getElementById('ggl').style.height = init_height + "px";
            document.getElementById('ggMap').style.display="block";	
            document.getElementById('ggl').style.visibility="visible";    
            
      	    g_map.checkResize();
      	    
      	    

      	    
      	    
      	    if (init_height < 290) {
	    	    g_map.removeControl(current_gmap_control);
	    	    current_gmap_control = new GSmallMapControl();
	    	    g_map.addControl(current_gmap_control);
	            } else {
	    	        g_map.removeControl(current_gmap_control);
	    	        current_gmap_control = new GLargeMapControl();
	                g_map.addControl(current_gmap_control);
	            }

        }
        else
        {
            document.getElementById('ggMap').style.display="none";	
            document.getElementById('ggl').style.visibility="hidden"; 
        }
        if (YYVisible)
        {
    	    document.getElementById('yhMap').style.width = init_width + "px";
    	    document.getElementById('YahooMap').style.width = init_width + "px";
	        document.getElementById('YahooMap').style.height = init_height + "px";
	        document.getElementById('yhMap').style.height = init_height + "px";
	        document.getElementById('yhMap').style.display="block";	
			document.getElementById('YahooMap').style.visibility="visible";
			YahooMap.resizeTo(new YSize(init_width, init_height));	
        }
        else
        {
            document.getElementById('yhMap').style.display="none";	
		    document.getElementById('YahooMap').style.visibility="hidden";  
		      }
        if (VEVisible)
        {
    	    document.getElementById('VeMap').style.width = init_width + "px";
    	    document.getElementById('ve').style.width = init_width + "px";
	        document.getElementById('ve').style.height = init_height + "px";
            document.getElementById('VeMap').style.height = init_height + "px";
            document.getElementById('VeMap').style.display="block";	
			document.getElementById('ve').style.visibility="visible";   

        /** Realign the position of the Mini Map so it appears
        where we want it - The Upper Right Corner*/
        var minimap = document.getElementById("MSVE_minimap");
        var xoffset = (document.getElementById("ve").offsetWidth - minimap.offsetWidth);
        if (mapcount == 1)
            ve_map.ShowMiniMap(xoffset, 0, VEMiniMapSize.Large );        
        else
            ve_map.ShowMiniMap(xoffset, 0, MiniMapSize);
 
        /**Hide the Mini Map resizer so the Mini Map cannot be resized*/
        document.getElementById("MSVE_minimap_resize").style.display = "none";			 
        ve_map.Resize(init_width, init_height);	
 			
			

			
			    }
        else
        {
           document.getElementById('VeMap').style.display="none";	
           document.getElementById('ve').style.visibility="hidden";	
        }        


	/**    if (mapcount ==1 || mapcount ==2)
	       document.getElementById('srch').style.width = Math.floor(document.body.clientWidth - 5) + "px";
	    else
	        document.getElementById('srch').style.width = (Math.floor((document.body.clientWidth -10 ) / 2)) + "px";
     */  	    	    	
            document.getElementById('srch').style.height = ( Math.floor((document.body.clientWidth) / 2) ) + "px";
       	    	    	
	        document.getElementById('srch').style.height = ( Math.floor(document.body.clientHeight ) / 2 ) + "px";



	

    }   catch(err)
    {
    /** alert("Error!SizeDivs",err.message); */
    }
    	
}	
	
	function ResizeDivs() {
	
	try
	{
		SizeDivs();
	    

    }
    catch(err)
    {
        /**alert("Error!ResizeDivs",err.message); */
    }
    }
    
	
	function ParseURL()
	{
	try
	{
	
	    var address = document.getElementById("search").value;
	    
        if (address.length == 0)
        {
           alert( "Please enter the location to search." );
           return;
        }
	    var mapcount =getMapCount();
	    if (mapcount == 0)
        {
           alert( "Please select atleast one map for making this search." );
           return;
        }	    
       if (GGVisible || YYVisible)
        {
		    g_geocoder.getLatLng(address, function(point) {
			    if (!point) {
				    /**alert(address + " not found");*/
			    } else {
				    g_map.setCenter(point, 13);
				     g_map.addOverlay(createNonDragableMarkeronGMap(point, 0, address));
				     var currentGeoPoint = new YGeoPoint(point.lat(), point.lng());
				     if (YYVisible)
				     {
				     			YahooMap.panToLatLon(currentGeoPoint);
			                    YahooMap.setZoomLevel(YahooZoomLevel(13));
			                	CreateMarkerOnYMap(currentGeoPoint,address);    
			          }

			    }
		    }
		    );
		    
          }
		
       if (VEVisible)
        {		
		    
		    ve_map.Clear();
            StartGeocoding(address); 
            
         }

	}   catch(err)
    {
        /**alert("Error!ParseURL",err.message); */
    }
		
}





	function ShowLocationByAddress(address)
	{


		setLatLonByAddress(address);
	}

	function setLatLonByAddress(address)
	{
		GoogleGeocoder.getLocations(address, setLatLonByAddressCallback);
	}

	function setLatLonByAddressCallback(response)
{
	try
	{


		if (!response || response.Status.code != 200) {
			alert("Sorry, Google was unable to geocode that address");
		} else {
			var lat = response.Placemark[0].Point.coordinates[1];
			var lng = response.Placemark[0].Point.coordinates[0];
			if (YYVisible)
			YahooPanTo(lat, lng);
			if (GGVisible)
			GooglePanTo(lat, lng);

            UpdateStatusforPosition(lat,lng)
		}
	}   catch(err)
    {
        alert("Error!setLatLonByAddressCallback",err.message); 
    }

		
	}
	
	

function UpdateStatusforPosition(lat,lng)
{

   CURRENT_LAT_POSITION = lat;
   CURRENT_LON_POSITION= lng;
            if(trackLatitude){
            document.getElementById("txtLatitude").value=lat;
			document.getElementById("txtLongitude").value=lng;
            }
		var YahooLinkMapTypes = new Array(3);
		YahooLinkMapTypes[MAP_TYPE_REG] = 'm';
		YahooLinkMapTypes[MAP_TYPE_SAT] = 's';
		YahooLinkMapTypes[MAP_TYPE_HYB] = 'h';

		var GoogleLinkMapTypes = new Array(3);
		GoogleLinkMapTypes[MAP_TYPE_REG] = '';
		GoogleLinkMapTypes[MAP_TYPE_SAT] = '&t=k';
		GoogleLinkMapTypes[MAP_TYPE_HYB] = '&t=h';

		var span = g_map.getBounds().toSpan();
         CURRENT_ZOOM_LEVEL  = getZoomLevel();
        CURRENT_MAP_TYPE2= ResolveMapType(CURRENT_MAP_TYPE);
        var statestring = CURRENT_LAT_POSITION + ',' + CURRENT_LON_POSITION + ',' + CURRENT_ZOOM_LEVEL + ',' + CURRENT_MAP_TYPE2;
		document.location.hash = statestring;
        document.getElementById("linkkookupid").innerHTML ='<a  title="view links in yahoo, msn and google" id="positionlink2" href="#' + statestring + '"> Position: [Lat: ' + CURRENT_LAT_POSITION.toString().substring(0,8) + ', Lon: ' + CURRENT_LON_POSITION.toString().substring(0,8) + '], MapType: ' + CURRENT_MAP_TYPE2 + ', Zoom: ' + CURRENT_ZOOM_LEVEL +  '</a>';;

}


function  UpdateStatusforZoom(v_Zoom)
{


        CURRENT_ZOOM_LEVEL  = getZoomLevel();
        CURRENT_MAP_TYPE2= ResolveMapType(CURRENT_MAP_TYPE);
        var statestring = CURRENT_LAT_POSITION + ',' + CURRENT_LON_POSITION + ',' + CURRENT_ZOOM_LEVEL + ',' + CURRENT_MAP_TYPE2;
		document.location.hash = statestring;
        document.getElementById("linkkookupid").innerHTML ='<a  title="view links in yahoo, msn and google" id="positionlink2" href="#' + statestring + '"> Position: [Lat: ' + CURRENT_LAT_POSITION.toString().substring(0,8) + ', Lon: ' + CURRENT_LON_POSITION.toString().substring(0,8) + '], MapType: ' + CURRENT_MAP_TYPE2 + ', Zoom: ' + CURRENT_ZOOM_LEVEL +  '</a>';;

}


function  UpdateStatusforMapType(yahoo_type)
{

        CURRENT_ZOOM_LEVEL  = getZoomLevel();
        CURRENT_MAP_TYPE = yahoo_type;
        CURRENT_MAP_TYPE2= ResolveMapType(yahoo_type);

        var statestring = CURRENT_LAT_POSITION + ',' + CURRENT_LON_POSITION + ',' + CURRENT_ZOOM_LEVEL + ',' + CURRENT_MAP_TYPE2;
		document.location.hash = statestring;
        document.getElementById("linkkookupid").innerHTML ='<a  title="view links in yahoo, msn and google" id="positionlink2" href="#' + statestring + '"> Position: [Lat: ' + CURRENT_LAT_POSITION.toString().substring(0,8) + ', Lon: ' + CURRENT_LON_POSITION.toString().substring(0,8) + '], MapType: ' + CURRENT_MAP_TYPE2 + ', Zoom: ' + CURRENT_ZOOM_LEVEL +  '</a>';;

}

function ResolveMapType(mapType)
{
if (mapType == YAHOO_MAP_HYB)
    return 'Hybrid';
else if (mapType == YAHOO_MAP_SAT)
    return 'Sattelite';
else(mapType == YAHOO_MAP_REG)
    return 'Normal';
}
  

    function AddPushpin()
      {
          var shape = new VEShape(VEShapeType.Pushpin, ve_map.GetCenter());
          shape.SetTitle('My pushpin');
          shape.SetDescription('This is shape number '+pinid);
          pinid++;
		  ve_map.AddShape(shape);
		  var shape = new VEShape(VEShapeType.Pushpin, ve_map.GetCenter());
          shape.SetTitle('My pushpin');
          shape.SetDescription('This is shape number '+pinid);		  
   		  minimap.AddShape(shape);		  
      }

      function AddPolyline()
      {
         var ll = ve_map.GetCenter();
         var lat = ll.Latitude;
         var lon = ll.Longitude;

         var shape = new VEShape(VEShapeType.Polyline, [new VELatLong(lat-0.1,lon-0.1),
                                                   new VELatLong(lat+0.1,lon-0.1),
                                                   new VELatLong(lat+0.1,lon),
                                                   new VELatLong(lat-0.1,lon),
                                                   new VELatLong(lat-0.1,lon+0.1),
                                                   new VELatLong(lat+0.1,lon+0.1)]);
         shape.SetTitle('My polyline');
         shape.SetDescription('This is shape number '+pinid);
         pinid++;
		 ve_map.AddShape(shape);
         var shape = new VEShape(VEShapeType.Polyline, [new VELatLong(lat-0.1,lon-0.1),
                                                   new VELatLong(lat+0.1,lon-0.1),
                                                   new VELatLong(lat+0.1,lon),
                                                   new VELatLong(lat-0.1,lon),
                                                   new VELatLong(lat-0.1,lon+0.1),
                                                   new VELatLong(lat+0.1,lon+0.1)]);
         shape.SetTitle('My polyline');
         shape.SetDescription('This is shape number '+pinid);
         pinid++;
		 minimap.AddShape(shape);
      }
      
      function AddPolygon()
      {
         var ll = ve_map.GetCenter();
         var lat = ll.Latitude;
         var lon = ll.Longitude;

         var shape = new VEShape(VEShapeType.Polygon, [new VELatLong(lat,lon-0.15),
                                                   new VELatLong(lat+0.1,lon-0.05),
                                                   new VELatLong(lat+0.1,lon+0.05),
                                                   new VELatLong(lat,lon+0.15),
                                                   new VELatLong(lat-0.1,lon+0.05),
                                                   new VELatLong(lat-0.1,lon-0.05)]);
         shape.SetTitle('My polygon');
         shape.SetDescription('This is shape number '+pinid);
         pinid++;
		 ve_map.AddShape(shape);
         var shape = new VEShape(VEShapeType.Polygon, [new VELatLong(lat,lon-0.15),
                                                   new VELatLong(lat+0.1,lon-0.05),
                                                   new VELatLong(lat+0.1,lon+0.05),
                                                   new VELatLong(lat,lon+0.15),
                                                   new VELatLong(lat-0.1,lon+0.05),
                                                   new VELatLong(lat-0.1,lon-0.05)]);
         shape.SetTitle('My polygon');
         shape.SetDescription('This is shape number '+pinid);
         pinid++;
		 minimap.AddShape(shape);
      }      
	
function GetRoute()
{        
   try
   {     

		txtFrom = document.getElementById("txtFrom").value;
		txtTo = document.getElementById("txtTo").value;

 	    var mapcount =getMapCount();
	    if (mapcount == 0)
        {
           alert( "Please select atleast one map for making this search." );
           return;
        }       
        if (txtFrom.length == 0)
        {
           alert( "Please enter the starting location for directions." );
           return;
        }
        if (txtTo.length == 0)
        {
           alert( "Please enter the destination location to see directions." );
           return;
        }
        var LatLong = null;
        var routeType = null;
                
		if(txtFrom != "" && txtTo != "")
		{
		   
		    LatLong = GetLatLong(txtFrom);
		    if(LatLong == "Error")
            {
                alert("Invalid Value :", txtFrom);
                return false;
            }
            if(LatLong != txtFrom)
                txtFrom = LatLong;                
            
            LatLong = GetLatLong(txtTo);
            if(LatLong == "Error")
            {
                alert("Invalid Value :", txtTo);
                return false;
            }
            if(LatLong != txtTo)
                txtTo = LatLong;
            
            var strRouteType = document.getElementById("rdoShortest");
            if (strRouteType != null)
            {
                if(strRouteType.checked)
                    routeType = VERouteType.Shortest;
                else
                    routeType = VERouteType.Quickest;
            }
            else
            {
               strRouteType = "Shortest";
               if(strRouteType == 'Shortest')
                    routeType = VERouteType.Shortest;
               else
                    routeType = VERouteType.Quickest;
            }
            
            
       
            var unit;
            var strRouteMeasure = document.getElementById("rdoKms");
            if (strRouteMeasure != null)
            {
                if(strRouteMeasure.checked)
                    unit = VERouteDistanceUnit.Kilometer;
                else
                    unit = VERouteDistanceUnit.Mile;
            }
            else
            {
               strRouteMeasure = "Miles";
               if(strRouteMeasure == 'Miles')
                    unit = VERouteDistanceUnit.Mile;
               else
                    unit = VERouteDistanceUnit.Kilometer;
            }            
                

                
            
            


var locations;


	      locations = new Array(txtFrom, txtTo);



            var options = new VERouteOptions;

            options.DrawRoute      = true;

            options.SetBestMapView = true;

            options.RouteCallback  = onGotRoute;

            options.DistanceUnit   = unit;

            options.ShowDisambiguation = false;
            if (VEVisible || YYVisible)
            {
                document.getElementById("imgWaitM").style.visibility="visible";
                ve_map.DeleteRoute();
                ve_map.GetDirections(locations, options);           
            } 
            if (GGVisible)
            {
             document.getElementById("imgWait").style.visibility="visible";
            setDirections(txtFrom, txtTo, "en_US", unit);

            }
    
        }
        else
        {
            document.getElementById("imgWait").style.visibility="hidden";
            document.getElementById("imgWaitM").style.visibility="hidden";
            alert("Error!","You forgot to enter value in To/From text box.");
        }
    }
    catch(err)
   {
        alert("Error!GetRoute",err.message); 
   }
    


    }  


function onGotRoute(route)         
{       
   
   try
  {        
     
        document.getElementById("imgWaitM").style.visibility="hidden";
        if(route == null)
        {
            alert("Unable to find the route on Microsoft map, try again."); 
            return;
        }
        MapLoaded();
        
       
		var legs          = route.RouteLegs;
		var turns         = "<h3>Turn-by-Turn Directions</h3><p>";
		var leg           = null;
		var turnNum       = 0;  
		var totalDistance = 0;  
        

        var routeTime =0; 
        routeTime =  route.Time / 60;
		var routeinfo="";            
        routeinfo+="Total distance: <b>";            
        routeinfo+=   route.Distance.toFixed(1) + " ";            
        routeinfo+=   "</b> miles"  +"<br/>";    
        routeinfo+="Estimated driving time: <b>";            
        routeinfo+= routeTime.toFixed(1)  +"</b> min";                         
        
        var steps="";   
        var currentGeoPoint;         
        var legs = route.RouteLegs; 
        var gp ;         
        for(var i = 0; i < legs.length ;i++)               
        {               
        
        leg = legs[i];  
        
                  var turn        = null;  
                  var legDistance = null; 
                  var turntime = null;
                  for(var j = 0; j < leg.Itinerary.Items.length; j ++)
                  {
					turnNum++;

					turn = leg.Itinerary.Items[j];  


					legDistance    = turn.Distance;
					totalDistance += legDistance;

					turns += " (" + legDistance.toFixed(1) + " miles)";

					turntime =turn.Time / 60;

                    steps+="<p><a href='javascript:ve_map.SetCenter(new VELatLong(" +
                         turn.LatLong.Latitude +
                         "," +
                         turn.LatLong.Longitude +
                         "));'>";
                    steps+= turnNum +
                         ". " + turn.Text +
                         " (" + legDistance.toFixed(1)+"miles - " + turntime.toFixed(1) + " min )</a></p>";


					currentGeoPoint = new YGeoPoint(turn.LatLong.Latitude, turn.LatLong.Longitude);
					CreateMarkerOnYMap(currentGeoPoint,turn.Text);
					var gp = new GLatLng(turn.LatLong.Latitude,turn.LatLong.Longitude);

	                CreateDraggableMarkerOnGMap(gp,turn.Text,icon3);
            
     }
                  
         
            steps+= "</div>";               
        }
        routeinfo+="<br/><b>Steps:</b>"+steps;    
  
        if("" != "")
			routeinfo+="<br/><b>Note:</b><br/>"+ "";  
			   
			

			ZWDialog.Alert(routeinfo, "M Directions for " + txtFrom + " - " + txtTo);

		 
                               
                               
   }
    catch(err)
   {
   alert("Error!onGotRoute",err.message); 
	}
}

function GetLatLong(str)
{
    var ret = str;
    try
    {
		str = str.trim();
    }
      catch(err)
    {
        /**alert("Error!",err.message); */
    }
    if(str.substring(0,7).toLowerCase() == "latlong")
    {
        str = str.substring(str.indexOf("(") + 1 , str.length - 1);
        var latlong = str.split(",");
        latlong[0] = latlong[0].trim();        
        latlong[1] = latlong[1].trim();
        if(IsNumeric(latlong[0].trim()) && IsNumeric(latlong[1].trim()))
            return (new VELatLong(latlong[0].trim(), latlong[1].trim()));   
        else
            return "Error";     
    }
    return ret;   
}


function MapLoaded()
{

    try
	{
    		v_lat = ve_map.GetCenter().Latitude;
    		v_lon =  ve_map.GetCenter().Longitude;
    		v_zoom = ve_map.GetZoomLevel();

		if(GGVisible)
		g_map.setCenter(new GLatLng(v_lat, v_lon), GoogleZoomLevel(v_zoom));
		if(YYVisible)
		    {
		    YahooMap.panToLatLon(new YGeoPoint(v_lat, v_lon));
   		    YahooMap.setZoomLevel(YahooZoomLevel(v_zoom));
		    }
		/** if(VEVisible)
		DrawMiniMap();	*/	

		

		}   catch(err)
		{
        /**alert("Error!MapLoaded",err.message); */
		}

}


function GetClipBoard(Div) 
{

 var obj = document.getElementById(Div);
		window.clipboardData.setData("Text", obj.innerText);		

}
   

function printAlert(div)
{


	var a = window.open('','','menubar=1,scrollbars=1,width=400,height=300');	
	a.document.open("text/html");
	a.document.write('<html><head><style type="text/css">body{font:normal 10px verdana,arial;} #frame{background-image:none;background-color:#FFFFFF;}</style></head><body style="padding-left:20px;background-image:none;background-color:#FFFFFF;">');
    a.document.write(document.getElementById(div).innerHTML);
    a.document.write('</body></html>');
    a.document.close();	
	a.print();
}



function CreateMarkerOnYMap(geoPoint, landmark){
    var newMarker= new YMarker(geoPoint);
    newMarker.addAutoExpand(landmark);
    var markerMarkup = "<font style='font-size: small; color: dimgray'>" + landmark + "</font>" ;

    YEvent.Capture(newMarker, EventsList.MouseClick, function(){newMarker.openSmartWindow(markerMarkup);});
    YahooMap.addOverlay(newMarker);


}



    function setDirections(fromAddress, toAddress, locale, DistanceUnit) {
    

    
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { getPolyline:true });
    }
    
    

    function handleErrors(){
        document.getElementById("imgWait").style.visibility="hidden";
            document.getElementById("zd_dlg_dialog_A").style.display="block"
            document.getElementById("zd_dlg_dialog_A").style.visibility="visible";
            document.getElementById("DTitle").innerHTML = "G Directions for " + txtFrom + " - " + txtTo;
            makeitdraggable('zd_dlg_dialog_A','zd_dlg_handle_A');
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     document.getElementById("ZdDlgtext").innerHTML = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code;
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	      document.getElementById("ZdDlgtext").innerHTML = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code;
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	      document.getElementById("ZdDlgtext").innerHTML = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code;

	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	      document.getElementById("ZdDlgtext").innerHTML = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code;

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	      document.getElementById("ZdDlgtext").innerHTML = "A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;
	    
	   else {
          document.getElementById("ZdDlgtext").innerHTML = " Unable to Search the route for the given locations. Google might not support search for these locations!!!" ;          

	   }
	   

	}

	function onGDirectionsLoad(){ 
        document.getElementById("imgWait").style.visibility="hidden";
        document.getElementById("zd_dlg_dialog_A").style.display="block"
        document.getElementById("zd_dlg_dialog_A").style.visibility="visible";
        document.getElementById("DTitle").innerHTML = "G Directions for " + txtFrom + " - " + txtTo;
        makeitdraggable('zd_dlg_dialog_A','zd_dlg_handle_A');
        if (poly) g_map.removeOverlay(poly);
        poly = gdir.getPolyline();
        g_map.addOverlay(poly);


	}
	
	
	var popupevent;
	/***************POPUP CONTEXTMENU FUNCTIONS*******/
var side='right';
function removepopupmenu(e){
	var menu = document.getElementById('popupmenu');
	menu.style.display='none';
}

function popupmenuforVE(e){

     var loc = ve_map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
     UpdateStatusforPosition(loc.Latitude,  loc.Longitude);

if (e.rightMouseButton)
{
	popupevent = e;
	var menuwidth=130;
	var menuheight=200;
	
	var xpos = e.mapX;
	var ypos = e.mapY;
	var menu = document.getElementById('popupmenu');
	menu.style.display='block';
	if(xpos+menuwidth > screen.width)xpos = screen.width-menuwidth;
	
	menu.style.left = xpos;
	menu.style.top = ypos;

	side = (xpos > ve_map.width-menuwidth*1) ? 'left' : 'right';
	}
	
	if (e.leftMouseButton)
	{
	removepopupmenu(e)
	}
		if (searchmode)
			{
		var ppoint =  new GLatLng();



		var pixel = new VEPixel(e.mapX, e.mapY);
		var LL = ve_map.PixelToLatLong(pixel);
		var ppoint = new GLatLng(LL.Latitude, LL.Longitude);		

		
			if (ppoint) {
				if (state == 1) { doEnd(ppoint) }
				if (state == 0) { doStart(ppoint) }
				}
		        
			}
     handleState();
}
/************************************************/
function ShowPopupMenuForGMAP(point, src, overlay)
{
			var v_lat, v_lon;
		v_lat = point.x;
		v_lon = point.y;
        UpdateStatusforPosition(v_lat,v_lon);
      handleState(point, src, overlay);

	var menuwidth=130;
	var menuheight=200;
	var xpos = document.getElementById('ggl').offsetLeft + point.x;
	var ypos = document.getElementById('ggl').offsetTop + point.y;
	var menu = document.getElementById('popupmenu');
	menu.style.display='block';
	if(xpos+menuwidth > screen.width)xpos = screen.width-menuwidth;
	menu.style.left = xpos;
	menu.style.top = ypos;

	side = (xpos > g_map.width-menuwidth*1) ? 'left' : 'right';
	
	
	


}

function RemovePopMenuForGMAP(overlay,point)
{
		try
		
		{
		var v_lat, v_lon;
		v_lat = point.y;
		v_lon = point.x;
        UpdateStatusforPosition(v_lat,v_lon);

	var menu = document.getElementById('popupmenu');
	menu.style.display='none';
	  if (searchmode)
	  {
	  if (point) {
          if (state == 1) { doEnd(point) }
          if (state == 0) { doStart(point) }
        }
      }
     handleState();
     }
     catch(ex)
     {
     }
	
}




function ShowPopupMenuForYMAP(_e, _c)
{
		var v_lat, v_lon;
		v_lat = _c.Lat;
		v_lon = _c.Lon;
        UpdateStatusforPosition(v_lat,v_lon);
/**	var menuwidth=130;
	var menuheight=200;
	var xpos = document.getElementById('YahooMap').offsetLeft + _e.thisObj.YCoordPoint.x;
	var ypos = document.getElementById('YahooMap').offsetTop + _e.thisObj.YCoordPoint.y;
	var menu = document.getElementById('popupmenu');
	menu.style.display='block';
	if(xpos+menuwidth > screen.width)xpos = screen.width-menuwidth;
	menu.style.left = xpos;
	menu.style.top = ypos;

	side = (xpos > g_map.width-menuwidth*1) ? 'left' : 'right'; */

}



      function swapMarkers(i) {
      try
     {
        g_map.removeOverlay(gmarkers[i]);
        DeleteOneShape(vmarkers[i]);
       
        createMarker(path[i],i,icon2);
		}   catch(err)
		{
			/**alert("Error!",err.message); */
		}
        
     }
      
         function DeleteOneShape(shape)
         {

            ve_map.DeleteShape(shape);
         }      

      var baseIcon = new GIcon(G_DEFAULT_ICON);
      baseIcon.iconSize=new GSize(24,38);

      var icon1 = G_START_ICON;
      var icon2 = G_PAUSE_ICON;
      var icon3 = G_END_ICON;
      var icon4 = new GIcon(baseIcon,"http://labs.google.com/ridefinder/images/mm_20_white.png");
          icon4.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
          icon4.iconSize = new GSize(12, 20);
          icon4.shadowSize = new GSize(22, 20);
          icon4.iconAnchor = new GPoint(6, 20);
          icon4.infoWindowAnchor = new GPoint(5, 1);


      function createMarker(point,i,icon) {
     
     try{
        var marker = new GMarker(point, {draggable:true,icon:icon});
        gmarkers[i]=marker;
        GEvent.addListener(marker, "dragend", function() {
          path[i] = marker.getPoint();
          if (!active[i]) {
            setTimeout('swapMarkers('+i+')', 1000);
          }
          active[i] = true;
          addresses[i] = "";
        });
        g_map.addOverlay(marker);
        

        var y = new VELatLong(point.lat(),point.lng());
        
          var shape = new VEShape(VEShapeType.Pushpin, y);
          
			
           
          shape.SetTitle('Route Search pushpin');
          shape.SetDescription('This is shape number '+pinid);
          shape.Id = pinid;
          vmarkers[i]=shape;          
          pinid++;
		  ve_map.AddShape(shape);
	}   catch(err)
    {
       /**alert("Error!createMarker",err.message); */
    }
		  
      }
      
      function CreateDraggableMarkerOnGMap(point,gtitle,icon) {
     
     try{
        var marker = new GMarker(point, {draggable:true,icon:icon, title:gtitle});
GEvent.addListener(marker,"mouseover", function() {
              marker.openInfoWindowHtml('step [data from MSN]' + '<br>'+'<b>' + gtitle + '</b>' );
          });

        g_map.addOverlay(marker);
        

	}   catch(err)
    {
        /**alert("Error!createMarker",err.message); */
    }
		  
      }
      

      var path = [];
      var active = [true,false,false,false,true];
      var gmarkers = [];
      var vmarkers = [];
      var addresses = [];

      var state = 0;

      function handleState() {

        if (state == 0) {
			document.getElementById("selectsearchpos").innerHTML = "Select Start";
        }
        if (state == 1) {
			document.getElementById("selectsearchpos").innerHTML = "Select End";
        }
        if (state == 2) {
			document.getElementById("selectsearchpos").innerHTML = "Drags the Pins as required";
        }        

                                                       
    }



      function doStart(point) {
      if (searchmode)
      {
        createMarker(point,0,icon1);
        path[0] = point;
        state = 1;
        handleState();
		}
		searchmode = false;
        
      }

      function doEnd(point) {
      if (searchmode)
      {      
        createMarker(point,4,icon3);
        path[4] = point;
        state = 2;
        handleState();
        for (var i=1; i<4; i++) {
          var lat = (path[0].lat()*(4-i) + path[4].lat()*i)/4;
          var lng = (path[0].lng()*(4-i) + path[4].lng()*i)/4;
          var p = new GLatLng(lat,lng);
          createMarker(p,i,icon4);
          path[i] = p;
        }
        bounds.extend(path[0]);
        bounds.extend(path[4]);
        g_map.setZoom(g_map.getBoundsZoomLevel(bounds));
        g_map.setCenter(bounds.getCenter());
       }
		searchmode = false;
		document.getElementById('searchPopupmnu').style.display='block';
      }







      function directions() {
      

      try{
     
      var x;
      var mySplitResult;
      
      		document.getElementById('searchPopupmnu').style.display='none';
           var menu = document.getElementById('popupmenu');
	menu.style.display='none';
	
	locations = new Array();
        if (addresses[0]) {
        var a = addresses[0] + "@" + path[0].toUrlValue(6);
        

        var mySplitResult =a.split(",");
        var x = new VELatLong(mySplitResult[0],mySplitResult[1]);
        locations.push(x);
        }
          else {
          var a = path[0].toUrlValue(6);

        var mySplitResult = a.split(",");
        var x = new VELatLong(mySplitResult[0],mySplitResult[1]);
        locations.push(x);
          
          } 
        if (addresses[4]) {
        
        var b = addresses[4] + "@" + path[4].toUrlValue(6);
        var mySplitResult = path[4].toUrlValue(6).split(",");
        var x = new VELatLong(mySplitResult[0],mySplitResult[1]);
        locations.push(x);
        }
          else {
          var b = path[4].toUrlValue(6);
          
        var mySplitResult =b.split(",");
        var x = new VELatLong(mySplitResult[0],mySplitResult[1]);
        locations.push(x);         
          
          } 
        for (var i=3; i>0; i--) {
          if (active[i]) {
            b = path[i].toUrlValue(6) +" to: "+b;
            
        var mySplitResult =path[i].toUrlValue(6).split(",");
        var x = new VELatLong(mySplitResult[0],mySplitResult[1]);
        locations.push(x);       
          }
        }
        
      var a = "from: "+a + " to: " + b;
        gdir.load(a, {getPolyline:true});
		var unit;
            var strRouteMeasure = document.getElementById("rdoKms");
            if (strRouteMeasure != null)
            {
                if(strRouteMeasure.checked)
                    unit = VERouteDistanceUnit.Kilometer;
                else
                    unit = VERouteDistanceUnit.Mile;
            }
            else
            {
               strRouteMeasure = "Miles";
               if(strRouteMeasure == 'Miles')
                    unit = VERouteDistanceUnit.Mile;
               else
                    unit = VERouteDistanceUnit.Kilometer;
            } 
                
	      
        
            var options = new VERouteOptions;

            options.DrawRoute      = true;

            options.SetBestMapView = true;

            options.RouteCallback  = onGotRoute;

            options.DistanceUnit   = unit;

            options.ShowDisambiguation = false;
            ve_map.DeleteRoute();
            ve_map.GetDirections(locations, options);    
             }   catch(err)
			{
				/**alert("Error!directions",err.message); */
			}

      }
      
      function choosestartend(point, src, overlay)
      
{
	searchmode = true;
 	var menu = document.getElementById('popupmenu');
	menu.style.display='none';


}




     
     
 function processvisibleMaps(){
		if (document.getElementById('chkGG').checked)
				 GGVisible= true;
		else
		     GGVisible= false;
		     
		if (document.getElementById('chkYY').checked)
				 YYVisible= true;
		else
			     YYVisible= false;	

		if (document.getElementById('chkVE').checked)
				 VEVisible= true;	
		else
			     VEVisible= false;
			     
			     ResizeDivs();
			     
			     			

		
		 
}

    
    /** msn maps serarch location */
    
         function StartGeocoding(address)
         {
            ve_map.Find(null,         /** what */
                  address,           /**  where  */
                  null,              /**  VEFindType (always VEFindType.Businesses) */
                  null,              /**  VEShapeLayer (base by default) */
                  null,              /**  start index for results (0 by default) */
                  null,              /**  max number of results (default is 10) */
                  null,              /**  show results? (default is true) */
                  null,              /**  create pushpin for what results? (ignored since what is null) */
                  null,              /** use default disambiguation? (default is true) */
                  null,              /**  set best map view? (default is true) */
                  GeocodeCallback);  /**  call back function */
         }
         
         function GeocodeCallback(shapeLayer, findResults, places, moreResults, errorMsg)
         {
            var resHtml = "";

            /**  if there are no results, display the error message and return */
            if (places == null)
            {
               alert( (errorMsg == null) ? "There were no results" : errorMsg );
               return;
            }

            /**  Create an entry for each VEPlace in the result set */
            for (var p = 0; p < places.length; p++)
            {
               /**  Gather some info up front */
               var place = places[p];
               var location = place.LatLong;
               var confString = confidenceStrings[place.MatchConfidence];
               var precString = precisionStrings[place.Precision];
               var mcVal = MatchCode(place.MatchCode);
               var latitude = location.Latitude;
               var longitude = location.Longitude;
               var title =  place.Name;
      
               /**  create the info box description */
               var desc = "Latitude: " + latitude + "<br/>" +
                          "Longitude: " + longitude;
               desc = desc + "<br>Confidence: " + confString;
               desc = desc + "<br>Precision: " + precString;
               desc = desc + "<br>Match Code: " + mcVal;
             
              createMarkerOnVE(latitude, longitude, p, title, desc,place.MatchConfidence)
              
      
               /**  Add the information to the resultsDiv html, including a link */
               /**  that recenters the map over the pin */
               resHtml = resHtml + 
                         "<p><a href='javascript:SetLocation(" +
                         latitude +
                         "," +
                         longitude +
                         ");'>";
               resHtml = resHtml + 
                         "#" + (p+1) +
                         ": " + place.Name +
                         " (" + precString +
                         ", " +
                         confString +
                         " confidence, " +
                         mcVal +
                         ")</a></p>";
            }
                    ZWDialog.Alert(resHtml, "M location results for " + document.getElementById("search").value)

         }
         
         
         
         function MatchCode(code)
         {
            if(code == VEMatchCode.None) {
               return "No match";
            }
   
            var codeDesc = "";   
            var cVal;
            
            cVal = code & VEMatchCode.Good;
            if(cVal > 0) {
              codeDesc += "Good ";
            }
   
            cVal = code & VEMatchCode.Ambiguous;
            if(cVal > 0) {
              codeDesc += "Ambiguous ";
            }
   
            cVal = code & VEMatchCode.UpHierarchy;
            if(cVal > 0) {
              codeDesc += "UpHierarchy ";
            }
   
            cVal = code & VEMatchCode.Modified;
            if(cVal > 0) {
              codeDesc += "Modified ";
            }
            
            return(codeDesc + "Match");
         }
/** ve map search location*/
/** create marker for google map */

        /**  Create a base icon for all of our markers that specifies the
        shadow, icon dimensions, etc. */
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);

        /**  Creates a marker whose info window displays the letter corresponding
        to the given index. */
        function createNonDragableMarkeronGMap(point, index, address) {
         /**  Create a lettered icon for this point using our icon class */
          var letter = String.fromCharCode("A".charCodeAt(0) + index);
          var letteredIcon = new GIcon(baseIcon);
          letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

          /**  Set up our GMarkerOptions object  */
          markerOptions = { icon:letteredIcon };
          var marker = new GMarker(point, markerOptions);

          GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml("<font style='font-size: small; color: dimgray'>" + address + "</font>");
          });
          return marker;
        }
        function createMarkerOnVE(lat, lon, p, title, desc,confidence)
            {
                       /**  Create a pin at that location, list the latitude & longitude */
               var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(lat,lon));
               pin.SetCustomIcon("<img src='" + 
                                 pushpinUrls[confidence] + 
                                 "'><span class='pinText'>" + 
                                 (p+1) + 
                                 "</span>");
               pin.SetTitle(title);
               pin.SetDescription(desc);
               ve_map.AddShape(pin);
               
               }
               
               
               

