var geocoder = new GClientGeocoder();
	var map;
	var icon = new GIcon();

	var ctrlPrefix = 'StockListSearchResults_';
	var blnDebug  = false;	
	
	var sGlobalAddressOriginal = '';
	var sGlobalOriganisationName = '';
	var sGlobalAddressManipulated = '';
	var sGlobalMode = ''; 
	var bGlobalAddressVarsSet =false;
	var bGlobalAmbiguousLocation = false;
	var bGlobalGeoAccuracy = 0;		
	var gMapCanvasID = 'gMap';
	var sGlobalLat = '';
	var sGlobalLong = '';

	
	function setAddressVars(Mode, AddressOriginal, OriganisationName)
	{
	
		if (!(bGlobalAddressVarsSet))
		{
		sGlobalAddressOriginal = AddressOriginal;
		sGlobalOriganisationName = OriganisationName;	
		sGlobalMode = Mode;
		bGlobalAddressVarsSet = true;	
		}

	} // fx : 	setAddressVars()
			
			
			
	function loadGoogleMapAdmin(lat, lon, add) {				
		// VOID ADMIN ONLY
			
	} // fx : loadGoogleMap end 	
			
			
	function loadGoogleMapFrontEnd(lat, lon, iLetter) {			
				sGlobalLat = lat;
				sGlobalLong = lon;
				alertTrace('loadGoogleMap(' + lat + ',' +  lon + ') : start ');	
				alertTrace('test :  GBrowserIsCompatible');
				
			if (GBrowserIsCompatible()) {
				alertTrace('test :  GBrowserIsCompatible : true');				
				try
				{
				map = new GMap2(document.getElementById(gMapCanvasID));
				} catch(e)
				{				
				alertTrace(e.description  + '\n attempted to create map \n check the div canvas id is ' + gMapCanvasID);
				}	
				alertTrace('add controls : map.addControl(new GSmallMapControl()); : map.addControl(new GMapTypeControl()); ');	
				map.addControl(new GSmallMapControl());
				map.addControl(new GMapTypeControl());
				
				alertTrace('map.setCenter(new GLatLng(' + lat + ',' +  lon + '), 15)');
				map.setCenter(new GLatLng(lat, lon), 15);				
		    	alertTrace('map.setCenter : done');    
		
		
				var point = new GLatLng(lat, lon);	
				//HERE
				var letter = String.fromCharCode("A".charCodeAt(0) + eval(iLetter));
				//alert(iLetter);
				//alert(letter);
				var letteredIcon = new GIcon(G_DEFAULT_ICON);										
				letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";																		
												
				marker = new GMarker(point, letteredIcon);
				map.addOverlay(marker);		
		
				
				alertTrace('point created');				
				
			//	shtmlInfo = formatFinalDisplayInfoBubble();
			//	marker.openInfoWindowHtml(shtmlInfo);	
			
			}	
		}	 // fx : loadGoogleMapFrontEnd end 
		
	
	function initLoadGoogleMapFrontEndByAddress(sAddress, iLetter)
	{
		var x;
		var y;		
		
		geocoder.getLatLng(
				sAddress,
				function(point) {
				if (!point) {
							bGlobalAmbiguousLocation = true;
							alertTrace('point not found : split address');
							var mySplitVal = sAddress.split(",");
							var newAddressVal = '';
							for(i = 1; i < mySplitVal.length; i++)
							{
							 newAddressVal += 	mySplitVal[i] + ',';						
							}							
							newAddressVal = newAddressVal.slice(0, -1);
							bGlobalGeoAccuracy = mySplitVal.length;
							alertTrace('retest with address :' + newAddressVal);						
							// WARNING :  RECURSIVE CALL HERE
							if ((bGlobalGeoAccuracy) >= 2)
							{	
							alertTrace('0 value = ' + mySplitVal[0] + '1 value = ' + mySplitVal[1] );		
							} 																	
							(bGlobalGeoAccuracy >= 2)?geoCode(mode, newAddressVal):alertTrace('Failed to find address');																																	
					} else {																															
							 loadGoogleMapFrontEnd(point.y, point.x, iLetter);																						
							 x = point.x;
							 y = point.y;
					} // else
				} // callback function
			);  //geocoder			
			initLoadGoogleMapFrontEnd(sAddress, x, y, iLetter);
	}
		
	function initLoadGoogleMapFrontEnd(sAddress, lat, lon, iLetter) {				
		if (lat != 0 && lon != 0) {
			sGlobalLat = lat;
			sGlobalLong = lon;			
			alertTrace('loadGoogleMap(' + lat + ',' +  lon + ') : start ');	
			alertTrace('test :  GBrowserIsCompatible');
		if (GBrowserIsCompatible()) {
			alertTrace('test :  GBrowserIsCompatible : true');				
			try
			{
			map = new GMap2(document.getElementById(gMapCanvasID));
			} catch(e)
			{				
			alertTrace(e.description  + '\n attempted to create map \n check the div canvas id is ' + gMapCanvasID);
			}	
			alertTrace('add controls : map.addControl(new GSmallMapControl()); : map.addControl(new GMapTypeControl()); ');	
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			
			alertTrace('map.setCenter(new GLatLng(' + lat + ',' +  lon + '), 15)');
			map.setCenter(new GLatLng(lat, lon), 9);				
		    alertTrace('map.setCenter : done');    
	
			var point = new GLatLng(lat, lon);
			alertTrace('point created');				
			var marker = null;
						
			var point = new GLatLng(arrPoint[1], arrPoint[0]);			
			var letter = String.fromCharCode("A".charCodeAt(0) + eval(iLetter));
			
			var letteredIcon = new GIcon(G_DEFAULT_ICON);		
			
			letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";		
			
			
			//alert(letteredIcon.image);
											
			marker = new GMarker(point, letteredIcon);
			map.addOverlay(marker);		
			
			/*var point = new GLatLng(arrPoint[1], arrPoint[0]);
			var letter = String.fromCharCode("A".charCodeAt(0) + i);
			var letteredIcon = new GIcon(G_DEFAULT_ICON);		
			
			letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";										
					
			var marker = new GMarker(point, letteredIcon);
			map.addOverlay(marker);*/
		
		}	
		}
	}	 // fx : loadGoogleMapFrontEnd end 							
	
	function initMap(sAddress, iLetter){
		try {			
		document.getElementById("map-header").style.display = "block";
		document.getElementById("btnPrint").style.display = "block";			
		} catch (ex) {}		
		initLoadGoogleMapFrontEndByAddress(sAddress, iLetter);	
	}
	
	function geoCode(mode, sAddress, orgTitle, latPoint, longPoint)
	{
		geoCode(mode, sAddress, orgTitle, latPoint, longPoint, 0);
	}
	
	function openPoup()
	{
		openPreview("StockListLocatorResultsPopUp.aspx?Points=" + document.getElementById("tbPointToPrint").value);
	}
	
	function test()
	{
		//alert("StockListLocatorResultsPopUp.aspx?" + document.getElementById("tbPointToPrint").value);		
		
		alert('in');
	}

	function geoCode(mode, sAddress, orgTitle, latPoint, longPoint, iLetter) {	
	
			var args = geoCode.arguments;
			var blnGeoCode = true;											
			setAddressVars(mode, sAddress, orgTitle);
			try{
			document.getElementById("map-header").style.display = "block";
			document.getElementById("btnPrint").style.display = "block";			
			}catch(ex){}
			
			if (args.length == 5) 
			{			
				if ((latPoint != 0) && (longPoint != 0)) 
				{					
					blnGeoCode = false;			
													
					loadGoogleMapFrontEnd(latPoint, longPoint, iLetter);
				}				
			}		
			
			alertTrace('geocoder.getLatLng();');
			
			if (blnGeoCode)
			{
			geocoder.getLatLng(
				sAddress,
				function(point) {
				
				if (!point) {
				
							bGlobalAmbiguousLocation = true;
							alertTrace('point not found : split address');
							var mySplitVal = sAddress.split(",");
							var newAddressVal = '';
							for(i = 1; i < mySplitVal.length; i++)
							{
							 newAddressVal += 	mySplitVal[i] + ',';						
							}							
							newAddressVal = newAddressVal.slice(0, -1);
							bGlobalGeoAccuracy = mySplitVal.length;
							alertTrace('retest with address :' + newAddressVal);						
							// WARNING :  RECURSIVE CALL HERE
							if ((bGlobalGeoAccuracy) >= 2)
							{	
							alertTrace('0 value = ' + mySplitVal[0] + '1 value = ' + mySplitVal[1] );		
							} 																	
							(bGlobalGeoAccuracy >= 2)?geoCode(mode, newAddressVal, orgTitle, latPoint, longPoint, iLetter):alertTrace('Failed to find address');																																	
					} else {									
							if (mode == 'admin')
							{					 							 
							 loadGoogleMapAdmin(point.y, point.x, sAddress);	
								if (!bGlobalAmbiguousLocation) 
								{										
									writeBackCoordinates(point.x, point.y, 'Driving function geoCode else point exists');
								}							
							} else if (mode=='frontend')
							{							
							
							 loadGoogleMapFrontEnd(point.y, point.x, eval(iLetter));	
							 document.getElementById("tbPointToPrint").value = point.y + ';' + point.x + ';' + sAddress + ';' + iLetter + ';' + orgTitle;							
							 //alert(document.getElementById("tbPointToPrint").value);
							 bGlobalAddressVarsSet =false;
							}
							
					} // else
								} // callback function
			);  //geocoder
			} // if blnGeoCode
						
			
			
		} // fx : geoCode end 

	function writeBackCoordinates(x,y, from)
		{
	// VOID ADMIN ONLY	
		
		}// fx : writeBackCoordinates end
	
	function formatFinalDisplayInfoBubble()
	{
					var sRetVal = '';	
					var orgTitleHtml = '';
					var originalAddress = '';
   				    originalAddress = sGlobalAddressOriginal;
					
					if (sGlobalOriganisationName != '')
					{ 	
					orgTitleHtml = "<strong>" +sGlobalOriganisationName + "</strong>";
					orgTitleHtml += "<br />";
					}					
					var mySplitVal = originalAddress.split(",");
					var newVal = '';
					// preserve the last comma elements		
					var intOffSet = 0;
					if (mySplitVal.length >= 2)
					{
						intOffSet = 2;
					} else {
						intOffSet = mySplitVal.length;
					}					
					for(i = 0; i < mySplitVal.length; i++)
					{
							if (i <= intOffSet)
							{
							newVal += 	mySplitVal[i] + '<br />';						
							} else {
							newVal += 	mySplitVal[i] + ', ';		
							}
					}
					newVal = newVal.slice(0, -2);				
					sRetVal = "<div style='font-family : Tahoma; color : Black; font-size : 12px; text-align:center;'>" + orgTitleHtml + newVal + "</div>";				
				   
				return sRetVal;
	}	// fx : formatFinalDisplayInfoBubble end

	function alertTrace(sVar)
	{
		 if (blnDebug == true)
		 {
			alert(sVar);
		 } 
	}// fx : alertTrace end
	
	//************* Error Handle **********************
	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.");
	   
	}
	//*************************************************
	
	//************* Directions **********************
	function getDirections()
	{
		try {			
			directionsPanel = document.getElementById("route");
			//clear panel before re-loading
			directionsPanel.innerHTML = "";
			directions = new GDirections(map, directionsPanel);
			
			//add listener for catching errors
			GEvent.addListener(directions, "error", handleErrors);
			
			//attempt load directions
			var tbFrom = document.getElementById("tbFrom");			
			//alert(sGlobalLat + ',' + sGlobalLong);
			directions.load("from: " + tbFrom.value + " to: " + sGlobalLat + ',' + sGlobalLong);								
						
		}catch(e){
			alert(e);
		}
	}
	//*************************************************