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);
if(YYVisible)
{
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;
var gmarkers = [];
var vmarkers = [];
var popupTitleKeys = [];
var popupTitles = []; /* use for virtual earth as they dont support infohtml type of gmap */
var popupDesc = [];
var lastpopBox = [];
var ResultBox = [];
/** check the visibility of maps*/
var GGVisible = true;
var YYVisible = false;
var VEVisible = false;
if (VEVisible)
var MiniMapSize = VEMiniMapSize.Small;
/** can also be set to VEMiniMapSize.Large    */

if(qs.get("lat") != null)
{
	lat = qs.get("lat");
	lon = qs.get("lon");
}
else
{
	var lat = 0;
	var lon = 0;
}

if(qs.get("zoom") != null)
{
	INITIAL_ZOOM_LEVEL = 18 - qs.get("zoom");
	CURRENT_ZOOM_LEVEL = INITIAL_ZOOM_LEVEL;
    CURRENT_YZOOM_LEVEL = qs.get("zoom");
}
else
{
	INITIAL_ZOOM_LEVEL = 13;
}

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;
var DEFAULT_LAT = lat;
var DEFAULT_LON  = lon;
function load(address)
{

	try
	{
		MAPLEADER = 'VE';
		if((lat == 0) || (lat == "") || (lat == null))
		{
			lat = document.getElementById("hidLat").value;
			DEFAULT_LAT =  lat;
		}

		if((lon == 0) || (lon == "") || (lon == null))
		{
			lon = document.getElementById("hidLon").value;
			DEFAULT_LON =  lon;
		}

		setZoomLevelConstant(INITIAL_ZOOM_LEVEL);
		GoogleGeocoder = new GClientGeocoder();
		init(lat, lon, INITIAL_ZOOM_LEVEL, CURRENT_MAP_TYPE);
         //setContext($find('AutoCompleteEx4').get_contextKey());	

	
		UpdateStatusforPosition(lat, lon);
		
	}

	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);
		document.getElementById("maps1").style.display="block";
		SizeDivs();
		showRouteSearch();
		g_map.setCenter(new GLatLng(lat, lng), GoogleZoomLevel(zoom));
	    document.getElementById("initdiv").style.display = 'none';
	}

	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)
{

if (!((v_lat != "null") && (v_lon != "null") && (v_lat != "") && (v_lon != "")))
{
v_lat = DEFAULT_LAT;
v_lon  = DEFAULT_LON;
}
	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.setZoomLevel(YahooZoomLevel(v_zoom))
		YahooMap.panToLatLon(new YGeoPoint(v_lat, v_lon));

		}

		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 == "")
			qs = location.hash;

		if(qs.length == 0)
			return;

		/** Turn <plus> back to <space>*/

	 
		qs = qs.replace(/\+/g, ' ');
		qs = qs.replace('?', '');
		qs = qs.replace('#', '');
		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)
{
//draggableCursor : "crosshair",
	try
	{

		       /**  var mapOptions = { googleBarOptions : { 
		          style : "new", adsOptions : {
		                client: "pub-4086457364603165",
                channel: "",
                adsafe: "high",
                language: "en"
              }
            }
           }*/
		if(GBrowserIsCompatible())
		{
			container = document.getElementById("ggl");

		/**g_map = new GMap2(container, mapOptions);
		  g_map.setCenter(new GLatLng(33.956461,-118.396225), 13);
			          g_map.setUIToDefault();
          
          g_map.enableGoogleBar();
          
          */
       			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(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));
			
var publisher_id = "pub-4086457364603165"; // Replace 1234123412341234 with your Google AdSense client id.

var adPos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT  , new GSize(7, 20)); // Set the anchor position and GSize offset to your desired values.

adsManagerOptions = {
maxAdsOnMap : 2,
style: 'adunit',
//channel: '12345678', // This field is optional - replace 12345678 with a channel number that you created for Google AdSense tracking
position: adPos
};

adsManager = new GAdsManager(g_map, publisher_id, adsManagerOptions);
adsManager.enable();

		}
	}

	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()
{
   htparam = 0;

	try
	{
		var mapcount = getMapCount();

			init_width = Math.floor((document.getElementById('maps1').clientWidth ) -5 / mapcount);
			init_height = Math.floor(document.getElementById('maps1').clientHeight) / mapcount;




		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);
			var yoffset = (document.getElementById("ve").offsetHeight - minimap.offsetHeight);
			if(mapcount == 1)
				ve_map.ShowMiniMap(xoffset, yoffset, VEMiniMapSize.Large);
			else
				ve_map.ShowMiniMap(xoffset, yoffset, 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";
		debugger;
		*/



    document.getElementById('ShowMapsMenu').style.left = document.body.clientWidth -370 + "px";
    //document.getElementById('ShowMapsMenu').style.top = document.body.clientTop  + "px";
    try
    {

    document.getElementById('AdDiv').style.left = document.body.clientWidth -150 + "px";
    document.getElementById('AdDiv').style.top = document.body.clientHeight - 320 + "px";
    }
    	catch(err){}
	
    try
    {
    document.getElementById('AdDiv2').style.left = document.body.clientWidth -900 + "px";
    document.getElementById('AdDiv2').style.top = document.body.clientHeight - 130 + "px";
    }
    	catch(err){}	
	}

	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;
	}


	CURRENT_ZOOM_LEVEL = getZoomLevel();
	CURRENT_MAP_TYPE2 = ResolveMapType(CURRENT_MAP_TYPE);
	var statestring = "?lat=" + CURRENT_LAT_POSITION + '&lon=' + CURRENT_LON_POSITION + '&zoom='  + CURRENT_ZOOM_LEVEL + '&maptype=' + CURRENT_MAP_TYPE2;

	document.location.hash = statestring;
	document.getElementById("menutitl").innerHTML = ' [?: ' + CURRENT_LAT_POSITION.toString().substring(0, 8) + ', f: ' + CURRENT_LON_POSITION.toString().substring(0, 8) + ']';;

}

function UpdateStatusforZoom(v_Zoom)
{
	CURRENT_ZOOM_LEVEL = getZoomLevel();
	CURRENT_MAP_TYPE2 = ResolveMapType(CURRENT_MAP_TYPE);
	var statestring = "?lat=" + CURRENT_LAT_POSITION + '&lon=' + CURRENT_LON_POSITION + '&zoom='  + CURRENT_ZOOM_LEVEL + '&maptype=' + CURRENT_MAP_TYPE2;

	document.location.hash = statestring;
	document.getElementById("menutitl").innerHTML = '?: ' + CURRENT_LAT_POSITION.toString().substring(0, 8) + ', f: ' + CURRENT_LON_POSITION.toString().substring(0, 8) + '';;

}

function UpdateStatusforMapType(yahoo_type)
{
	CURRENT_ZOOM_LEVEL = getZoomLevel();
	CURRENT_MAP_TYPE = yahoo_type;
	CURRENT_MAP_TYPE2 = ResolveMapType(yahoo_type);

	var statestring = "?lat=" + CURRENT_LAT_POSITION + '&lon=' + CURRENT_LON_POSITION + '&zoom='  + CURRENT_ZOOM_LEVEL + '&maptype=' + 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 == MAP_TYPE_HYB)
		return 'Hybrid';
	else
		if(mapType == MAP_TYPE_SAT)
			return 'Sattelite';
			else(mapType == MAP_TYPE_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
	{
		
		if(route == null)
		{
			alert("Unable to find the route on Microsoft map, try again.");
			return;
		}

		MapLoaded();
		var legs = route.RouteLegs;
		var turns = "<h3>Virtual Earth: Driving Directions " + FROM_STOP + " to " + TO_STOP + "</h3><p>";
		var leg = null;
		var turnNum = 0;
		var totalDistance = 0;
		var routeTime = 0;
		var turn = null;
		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 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;
				var mmCounter = GetMarkerCount() ; 
				steps += "<p><a href='javascript:onclick=MarkerClick(" + (mmCounter ) + ");'>";
				var ImageUrl = getAlternate1PushpinImage(j);
				var  numberImage ="<img style='cursor:pointer' src='" +  ImageUrl + "' />";	
				steps += numberImage + ". " + turn.Text + " (" + legDistance.toFixed(1) + "miles - " + turntime.toFixed(1) + " min )</a></p>";
                CreateMarketForMaps(turn.LatLong.Latitude, turn.LatLong.Longitude, ImageUrl,  turn.Text, "");

			}

			steps += "</div>";
		}

		routeinfo += "<br/><b>Steps:</b>" + steps;
		if("" != "")
			routeinfo += "<br/><b>Note:</b><br/>" + "";
			routeinfo = "<div class ='dlg' >" + routeinfo  + "</div>";
    var popupboxid1 = "rsltbx1" + (GetResultboxCount() + 1);
        ResultBox.push(popupboxid1);
    new popUp(300, 195, 300, 175, popupboxid1, routeinfo, "white", "lightgrey", "9pt sans-serif","VE: By Drive from " + FROM_STOP + " to " + TO_STOP, "#0084d8", "lightgrey", "gray", "#00468c", "black", true, true, true, true, false, false,'images/min.png','images/max.png','images/close.png','images/resize.jpg', true,'images/copy.png','images/print.png' );
  //  hidebox(popupboxid1);
  //  fadeboxin(popupboxid1);


	}

	catch(err)
	{
		alert("Error!onGotRoute:" + err.message);
	}
	
		try
	{

			GotoLocation(turn.LatLong.Latitude, turn.LatLong.Longitude, 13);
	}
		catch(err)
	{
		
	}
}

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
	}

	);
}




var popupevent;

/***************POPUP CONTEXTMENU FUNCTIONS*******/
var side = 'right';

function removepopupmenu(e)
{
return;
	var menu = document.getElementById('popupmenu');
	menu.style.display = 'none';
}

function popupmenuforVE(e)
{
clearMarkerPopups();
	var loc = ve_map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
	UpdateStatusforPosition(loc.Latitude, loc.Longitude);
	return;
	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);
	
	return;
	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 addresses = [];
var state = 0;

function handleState()
{
return;
	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  GetRouteByLatLon( flat, flon, tlat, tlon)
{
 if(GGVisible)
GetGoogleRouteByLatLon( flat, flon, tlat, tlon);
 if(VEVisible)
GetVERouteByLatLon( flat, flon, tlat, tlon)
}

function GetVERouteByLatLon( flat, flon, tlat, tlon){ 

try{

 if (ve_map == undefined)
	        {
	            drawVE(CURRENT_LAT_POSITION, CURRENT_LON_POSITION, CURRENT_ZOOM_LEVEL, CURRENT_MAP_TYPE);
	            document.getElementById('VeMap').style.display = "none";
			    document.getElementById('ve').style.visibility = "hidden";
	        }		
	     }
	     catch(err)
	     {}
	     MakeVisibleGGMap()

	try
	{
		var x;
            locations = new Array();
			var x = new VELatLong(flat, flon);
			locations.push(x);
			x = new VELatLong(tlat, tlon);
			locations.push(x);


		var unit;
		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 GetGoogleRouteByLatLon( flat, flon, tlat, tlon){ 


                gdir = new GDirections(g_map); 
                
            GEvent.addListener(gdir, "load", onGDirectionsLoad2);
			GEvent.addListener(gdir, "error", handleErrors);


var p = new GLatLng(flat, flon);
var q = new GLatLng(tlat, tlon);
                var pointsArray = [p,q]; 
                gdir.loadFromWaypoints(pointsArray,{getSteps: true, locale: "GB"}); 
        } 

//  3. Using Route, Steps, get the last step
function onGDirectionsLoad2(){



  var nrroutes = gdir.getNumRoutes();
 		for(var j = 0; j < nrroutes; j++)
		{   
            var route = gdir.getRoute(0);
            var nrsteps = route.getNumSteps();

            var steps = "";
            var turns = "<h3>Google Maps: By Drive  from " + FROM_STOP + " to " + TO_STOP + "</h3><p>";
            var routeinfo = "";
            routeinfo += turns + "Total distance: <b>";
            routeinfo += route.getSummaryHtml() + " ";

 		    for(var i = 0; i < nrsteps; i++)
		    {   
        
                var step = route.getStep(i);
                legDistance = step.getDistance();
                turns +=legDistance;
                var mmCounter = GetMarkerCount() ; 
                steps += "<p><a href='javascript:onclick=MarkerClick(" + (mmCounter ) + ");'>";
                var ImageUrl = getAlternate1PushpinImage(i);
                var  numberImage ="<img style='cursor:pointer' src='" +  ImageUrl + "' />";	
                steps += numberImage + ". " + step.getDescriptionHtml() + " (" + step.getDistance().html + " - " + step.getDuration().html  + " )</a></p>";
                CreateMarketForMaps(step.getLatLng().lat(), step.getLatLng().lng(), ImageUrl,  step.getDescriptionHtml(), "");
         
            }
    
        }
        steps += "</div>";
        routeinfo += "<br/><b>Steps:</b>" + steps;
        if("" != "")
        routeinfo += "<br/><b>Note:</b><br/>" + "";
        routeinfo = "<div class ='dlg' >" + routeinfo  + "</div>";
        var popupboxid1 = "rsltbx2" + (GetResultboxCount() + 1);
        ResultBox.push(popupboxid1);
        new popUp(300, 195, 300, 175, popupboxid1, routeinfo, "white", "lightgrey", "9pt sans-serif","GM: By Drive from " + FROM_STOP + " to " + TO_STOP, "#0084d8", "lightgrey", "gray", "#00468c", "black", true, true, true, true, false, false,'images/min.png','images/max.png','images/close.png','images/resize.jpg', true,'images/copy.png','images/print.png' );

}
// cuts out the street from the step.getDescriptionHtml()
// If the street is a highway the surrounding tags are <wbr> instead of <b>
function getStreet(str){
  var street = str.substring(str.lastIndexOf("<b>")+3,str.lastIndexOf("</b>"));
  if (street.lastIndexOf("/<wbr/>") > 0) {
    street = street.substring(0, street.lastIndexOf("/<wbr/>"));
  }
  return street;
}


// Not used right now
function generalize(street){
//  var temp = street.replace(/straat/,"");
//  temp = temp.replace(/sesteenweg/,"");
//  temp = temp.replace(/steenweg/,"");
//  temp = temp.replace(/weg/,"");
//  temp = temp.replace(/laan/,"");
//  temp = temp.replace(/rue/,"");
  return street;
}


//  5. This returns a number of matches (Placemarks)
//      Someroad, city 1, belgium, latlng point
//      Someroad, city 2, belguim, latlng point
function refine(response) {
  if (!response || response.Status.code != 200) {
    alert("Sorry, we were unable to geocode that address");
  }
  else {
    //  6. Use the distance between the original saved latlngpoint and each
    //     candidate, and select the one with minimum distance.
    var place = getBestMatchingPlacemark(response);
    //  7. Display the selected location and adress on the map.
    if (place != null) {
      var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
      var icon = new GMarker(lastpoint, {draggable: true});
      icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
      icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
      icon.iconSize = new GSize(12, 20);
      icon.shadowSize = new GSize(22, 20);
      icon.iconAnchor = new GPoint(6, 20);
      icon.infoWindowAnchor = new GPoint(5, 1);
          document.getElementById("message").innerHTML = lastpoint.toString();
      map.addOverlay(icon);
      icon.openInfoWindowHtml(place.address + '<br>' + '<b>Country code:</b> ' + 

place.AddressDetails.Country.CountryNameCode);
document.getElementById("address").innerHTML = place.address + '<br>' + '<b>Country code:</b> ' + 

place.AddressDetails.Country.CountryNameCode.toString();
       }
    else {
     //alert("Sorry, we were unable to geocode that address");
    }
  }
}


//  6. Use the distance between the original saved latlngpoint and each
//     candidate, and select the one with minimum distance.
function getBestMatchingPlacemark(response){
  var i = 0;
  var j = -1;
  // the result should be at least within 1 km.
  var mindist = 1000;
  for (i = 0; i < response.Placemark.length; i++){
    var place = response.Placemark[i];
    // Just listing the posibilties (todo : remove alert)
    alert(place.address);
    var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    var temp = lastpoint.distanceFrom(point);
    if (temp < mindist) {
      j = i;
      mindist = temp;
    }
  }
  if(j < 0 ) return null;
  return response.Placemark[j];
}

// handle GDirection errors
function handleErrors()
{
if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
alert("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)
alert("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)
alert("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_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//    alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    alert("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)
    alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

  else alert("An unknown error occurred.");

}

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 MakeVisibleYahooMap()
{
 sClear();
	if(document.getElementById('chkYY').checked)
	{
		YYVisible = true;
		    if (YahooMap == undefined)
	        {
	            loadYahoo(CURRENT_LAT_POSITION, CURRENT_LON_POSITION, CURRENT_ZOOM_LEVEL, CURRENT_MAP_TYPE);
	            YahooMap.panToLatLon(new YGeoPoint(CURRENT_LAT_POSITION, CURRENT_LON_POSITION));
			    YahooMap.setZoomLevel(YahooZoomLevel(CURRENT_ZOOM_LEVEL))
	            
	        }	
	         GotoLocation(CURRENT_LAT_POSITION, CURRENT_LON_POSITION, CURRENT_ZOOM_LEVEL);	
	}
	else
	{
		YYVisible = false;
	
	}


	ResizeDivs();
}


function MakeVisibleGGMap()
{
 sClear();
	if(document.getElementById('chkGG').checked)
    {
	    GGVisible = true;
	     if (g_map == undefined)
	        {
	        
	            drawGM(CURRENT_LAT_POSITION, CURRENT_LON_POSITION, CURRENT_ZOOM_LEVEL, CURRENT_MAP_TYPE);
	        }
	        GotoLocation(CURRENT_LAT_POSITION, CURRENT_LON_POSITION, CURRENT_ZOOM_LEVEL);
	}
	else
	{
		GGVisible = false;
				
    }

	ResizeDivs();
}


function MakeVisibleVEMap()
{
 sClear();
	if(document.getElementById('chkVE').checked)
	{

		VEVisible = true;
	    if (ve_map == undefined)
	        {
	            drawVE(CURRENT_LAT_POSITION, CURRENT_LON_POSITION, CURRENT_ZOOM_LEVEL, CURRENT_MAP_TYPE);
	        }		
	          GotoLocation(CURRENT_LAT_POSITION, CURRENT_LON_POSITION, CURRENT_ZOOM_LEVEL);
	}
	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, image, address)
{
           baseIcon.iconSize=new GSize(12,20);
//          baseIcon.shadowSize=new GSize(25,20);
//          baseIcon.iconAnchor=new GPoint(12,20);
//          baseIcon.infoWindowAnchor=new GPoint(16,0); 

	var letteredIcon = new GIcon(baseIcon);
	/**letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";*/
    letteredIcon.image = image;

	/**  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>");
	}

	);
	
	popupTitles.push(address);
	gmarkers.push(marker);	
	return marker;


	
}

function createMarkerOnVE(lat, lon, image, 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='" + image + "'>");
	/**pin.SetCustomIcon("<img src='" + pushpinUrls[confidence] + "'><span class='pinText'>" + (p + 1) + "</span>");	*/
	pin.SetTitle(title);
	pin.SetDescription(desc);
	vmarkers.push( new VELatLong(lat, lon));	
	ve_map.AddShape(pin);
	popupTitles.push(title + "<br/>" + desc);
}

function sClear()
{
    try
    {
    gmarkers = [];
    vmarkers = [];
    popupTitles = [];
    popupTitleKeys= [];
    if(GGVisible)
    g_map.clearOverlays();
    if(VEVisible)
    ve_map.DeleteAllShapes();
    if(YYVisible)
    YahooMap.removeMarkersAll();
    }
	catch(err)
	{

		/**alert("Error!directions",err.message); */
	}
    clearMarkerPopups();
    closeAllResultBoxes();	
}

function drawPolylineForGMap(points, color )
{
        var polyOptions = {geodesic:true};
        var polyline = new GPolyline(points, color, 2, 1, polyOptions);
        g_map.addOverlay(polyline);
        
        }

function drawPolylineForVEMap(points, color  )
{
    var polyline = new VEShape(VEShapeType.Polyline,points);
    var rgbcolor = hex2num(color);
    var red = rgbcolor[0];
    var green = rgbcolor[1];
    var blue = rgbcolor[2];
    polyline.HideIcon();
    polyline.SetLineColor(new VEColor(red,green,blue,1));
    polyline.SetFillColor(new VEColor(0,0,0,0));
    polyline.SetLineWidth(2);
    ve_map.AddShape(polyline);
   ve_map.SetMapView(points);
        
 }
        
function drawPolylineForYMap(points, color)
{


    YahooMap.addOverlay(new YPolyline(points,color,2,0.5));

        
}

function drawPolyline(LatLonStr )
{
		var arry = LatLonStr.split(','); /** parse out name/value pairs separated via &*/
		var VEpoints = new Array();
	    var GPoints = new Array();
        var YPoints=new Array();
        var colour;
        colour = random_color('hex'); /**"#ff0000";*/     
        
		/** split out each name=value pair */
		for(var i = 0; i < arry.length - 1; i++)
		{
			    var pair = arry[i].split('|');
			    
			    if ((pair[0] != "null") && (pair[1] != "null") && (pair[0] != "") && (pair[1] != "")) 
			    {
		        if(VEVisible)
                    VEpoints.push(new VELatLong(pair[0], pair[1]));

		        if(GGVisible)

		            GPoints.push( new GLatLng(pair[0], pair[1]));

		        if(YYVisible)
                    YPoints.push(new YGeoPoint(pair[0], pair[1]));
                 }
		}

                
               if(VEVisible)
                    drawPolylineForVEMap(VEpoints,colour);

		        if(GGVisible)
		            drawPolylineForGMap(GPoints,colour );

		        if(YYVisible)
                    drawPolylineForYMap(YPoints,colour );
      
}



/**Convert a hex value to its decimal value - the inputted hex must be in the
	format of a hex triplet - the kind we use for HTML colours. The function
	will return an array with three values. */
function hex2num(hex) {
	if(hex.charAt(0) == "#") hex = hex.slice(1); /**Remove the '#' char - if there is one.*/
	hex = hex.toUpperCase();
	var hex_alphabets = "0123456789ABCDEF";
	var value = new Array(3);
	var k = 0;
	var int1,int2;
	for(var i=0;i<6;i+=2) {
		int1 = hex_alphabets.indexOf(hex.charAt(i));
		int2 = hex_alphabets.indexOf(hex.charAt(i+1)); 
		value[k] = (int1 * 16) + int2;
		k++;
	}
	return(value);
}
/**Give a array with three values as the argument and the function will return
	the corresponding hex triplet. */
function num2hex(triplet) {
	var hex_alphabets = "0123456789ABCDEF";
	var hex = "#";
	var int1,int2;
	for(var i=0;i<3;i++) {
		int1 = triplet[i] / 16;
		int2 = triplet[i] % 16;

		hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2); 
	}
	return(hex);
}


function getPushpinImage(index)
{

	var ImageFld = "red";
	if ((index >= 99) && (index <199))
	{
	    ImageFld = "green";
	    index = index  - 99; 
	 }
	if ((index >= 199) && (index <299))
	{

	    ImageFld = "blue";
	    index = index  - 199; 
	}
//    return "pushpin/" + ImageFld +"/marker" + (index) + ".png";

return "pushpin/push_pin2.png";

}

function getAlternate1PushpinImage(index)
{

	var ImageFld = "red";
	if ((index > 99) && (index <200))
	{
	    ImageFld = "green";
	    index = index  - 99; 
	 }
//    return "pushpin/" + ImageFld +"/marker" + (index) + ".png";
return "pushpin/push_pin2.png";
}
function getAlternate2PushpinImage(index)
{

	var ImageFld = "blue";
	if ((index > 99) && (index <200))
	{
	    ImageFld = "yellow";
	    index = index  - 99; 
	 }
    //return "pushpin/" + ImageFld +"/marker" + (index) + ".png";
    return "pushpin/push_pin2.png";

}
      function GMarkerClick(i) {

        GEvent.trigger(gmarkers[i],"click");
      }
      
      
            function VMarkerClick(i) {
            
            ve_map.SetCenter(vmarkers[i]);
		v_lat = ve_map.GetCenter().Latitude;
		v_lon = ve_map.GetCenter().Longitude;

UpdateStatusforPosition(v_lat, v_lon);
var pixel = ve_map.LatLongToPixel(new VELatLong(v_lat,v_lon));
var xPixel = pixel.x;
var yPixel = pixel.y; 
clearMarkerPopups();

var popupboxid = "idmk1" + i;

lastpopBox.push(popupboxid);


new popUp(xPixel, yPixel, 150, 20, popupboxid,popupTitles[i], "white", "#00385c", "9pt serif", null, "#00385c", "white", "lightgrey", "#00568c", "black", true, false, false, false, false, false,'','','','');
/**new popUp(left_position, top_position, width, height, id_of_box, content_text, content_bgcolor, content_text_color, content_font_stylestring, title_text, title_bgcolor, title_text_color, border_color,  scrollbar_color, shadow_color, is_hidden_on_start, is_draggable, is_resizeable, show_old, is_external, disable_on_return , min_image, max_image, close_image, resize_image);*/
    hidebox(popupboxid);
    fadeboxin(popupboxid);

      }


      function MarkerClick(i) {
      if (GGVisible)
            GMarkerClick(i)
      if (VEVisible)
            VMarkerClick(i)
      }
      
function clearMarkerPopups()
{

		for(var p = 0; p < lastpopBox.length; p++)
	    {
	        try
	        {
            unloadbox(lastpopBox[p]);
	         }
	            catch(err){}
	    }
	    
	    lastpopBox = [];
  }
  
  
  function GetmarkerId(title)
{

var j =0;
		for(p = 0; p < popupTitleKeys.length; p++)
	    {
	        try
	        {
             if ( title == popupTitleKeys[p])
             {
                j = p;
                return j;
                }
             
	         }
	            catch(err){return 0;}
	    }
	   return j; 
  }
 
  function GetMarkerCount(title, desc)
  {

  
  if(GGVisible)
    return gmarkers.length;
   if(VEVisible)
    return vmarkers.length; 
  }
  
  
  
    function GetResultboxCount()
   {
     return ResultBox.length;
   }
  function closeAllResultBoxes()
  {

		for(var p = 0; p < ResultBox.length; p++)
	    {
	        try
	        {    
	        unloadbox(ResultBox[p]); 
	         }
	            catch(err){
	            }
	    }
	    ResultBox = [];
  }

  
  function CreateMarketForMaps(PChangeStopLat, PChangeStopLon, ImageUrl, title, desc)
    {
      var Mid = 0;
      Mid = GetmarkerId(title);
      if (Mid  != 0)
        return Mid;
        
        

        
 try
 {
  		        if(VEVisible)
		        {
			        createMarkerOnVE(PChangeStopLat, PChangeStopLon, ImageUrl, title, desc, 2);
		        }
		        if(GGVisible)
		        {
		            var bounds = new GLatLngBounds();

			        g_map.addOverlay(createNonDragableMarkeronGMap(new GLatLng(PChangeStopLat, PChangeStopLon), ImageUrl, title + "<br>" +  desc));
			        bounds.extend(new GLatLng(PChangeStopLat, PChangeStopLon));
                    g_map.fit(bounds);
        			
		        }
		        if(YYVisible)
		        {
			        CreateMarkerOnYMap(new YGeoPoint(PChangeStopLat, PChangeStopLon), title + "<br>" +  desc );	
		        }	
		            popupTitleKeys.push(title);   
		          if(GGVisible)
                    return gmarkers.length - 1;
                  if(VEVisible)
                    return vmarkers.length - 1; 
}
catch (e)
{}
  }
  
  
  
  /** @format (hex|rgb|null) : Format to return, default is integerfunction */
 function random_color(format)
  {
   var rint = Math.round(0xffffff * Math.random()); 
   var a;
   switch(format) 
   {  
    case 'hex':   
        a = ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');  
        break;

    case 'rgb':   
         a =  'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';  
     break;
    default:   
         a =  rint;  
     break;
    }
    return a;
   }
   
   function setContext(ctx)
   {
   debugger;
        $find('AutoCompleteEx').set_contextKey(ctx);
        $find('AutoCompleteEx2').set_contextKey(ctx);
        $find('AutoCompleteEx3').set_contextKey(ctx);
        $find('AutoCompleteEx4').set_contextKey(ctx); 
          switch(ctx) 
           {  
            case 'QZH':   
                GotoLocation(12.9832, 77.5833, 13);
                break;

            case 'PQT':   
                GotoLocation(13.07011,80.190238, 13);  
             break;
            case 'EQT':  
                GotoLocation(28.62671,77.251396, 13);  
                break;

            case 'LZH':   
                GotoLocation(17.4220632,78.509674, 13);  
             break;
            case 'OQT':  
                 GotoLocation(19.161384,72.982177, 13);  
             break;    
             case 'KIT':  
                 GotoLocation(18.5247014,73.857307, 13); 
             break;    
             case 'CKT':  
                 GotoLocation(22.56028,88.35290, 13); 
             break; 
            case 'IST':  
                 GotoLocation(22.72101,75.8599, 13); 
             break;                  
            default:   
               // showRouteSearch(); 
             break;
            }  
   }
   
       function doClick(buttonName,e)
    {
    


        var key;

         if(window.event)
              key = window.event.keyCode;     /**IE*/

         else
              key = e.which;     /**firefox */

    
        if (key == 13)
        {

            var btn = document.getElementById(buttonName);
            if (btn != null)
            { 

                btn.click();
                event.keyCode = 0
            }
        }
        
   }
          function doChange(e)
    {
    
           // document.getElementById("AdText").innerHTML ="Local listings for " + e.srcElement.value;    
           
   }
