var map;
var geocoder;
var branchName;
var locationCount;
var gcounter = 0;
var bounds = new GLatLngBounds();
var errorACheck = 0;
var addArray = new Array();
var addNotFound = new Array();
var nfcount = 0;	
	
function initialize() {
      map = new GMap2(document.getElementById("map_canvas"));
	 // We define the function first
		gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

function TextualZoomControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
TextualZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
	var container = document.createElement("div");
	var zoomOutDiv = document.createElement("div");
	this.setButtonStyle_(zoomOutDiv);
	container.appendChild(zoomOutDiv);
	zoomOutDiv.appendChild(document.createTextNode("Start"));
	GEvent.addDomListener(zoomOutDiv, "click", function() {
	//  map.zoomOut();
	map.setCenter(new GLatLng(-26.273714,135), 3);	
	map.closeInfoWindow();
	
	//map.clearOverlays();
  });

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "underline";
  button.style.color = "#0000cc";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "6em";
  button.style.cursor = "pointer";
}
	map.addControl(new TextualZoomControl());
// A TextualZoomControl is a GControl that displays textual "Zoom In"
// and "Zoom Out" buttons (as opposed to the iconic buttons used in
// Google Maps).
	map.addControl(new GSmallMapControl());
//map.addControl(new GMapTypeControl());
//http://maps.google.com/?ie=UTF8&ll=-26.273714,135.615234&spn=42.359288,96.328125&z=4&om=1
// this is australia longtitud and altitude!
	map.setCenter(new GLatLng(-26.273714,135), 3);
//Additional button to go back to the whole view..
	geocoder = new GClientGeocoder();
  
 }

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function createMarker(point, place, branchName) {

		// Create a lettered icon for this point using our icon class
		// Set up our GMarkerOptions object
		var baseIcon = new GIcon();
		baseIcon.image = "http://www.thegreenpages.com.au/images/gp-dot.png";
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(29, 32);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);

		markerOptions = { icon:baseIcon };
		
		
		//alert("getting the name of the branch" + branchName.firstChild.nodeValue);
		//alert("counting the global name counter: " + gcounter);
		
		//alert("the point we are adding the Point they are adding is " + point + "the current coutner is" + gcounter );
		var marker = new GMarker(point, markerOptions);
		
		//	var marker2 = new Gmarker(point, markerOptions);
		
		
		var baddress = place.address
		var branchadd=baddress.split(",")
		
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml("<b>Company Name:</b><br /><span style=\"font-size: 14px; color: #5fa841;\">" +  branchName +"</span><br /><br /><b>Address:</b><br />" + branchadd[0] + "<br />" + branchadd[1] + "<br />" + branchadd[2]);
			map.setZoom(16);
		}); 
		
		
		return marker;
}
 
function setDirections(fromAddress, toAddress, locale) {
		//alert ("getting the direction to that place");
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }

    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("Your address is not found, please re-enter in the address." + gdir.getStatus().code );
	   
	}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}


	
function createMarkerNotFound(point, place, branchName) {
		var baseIcon2 = new GIcon();
		baseIcon2.image = "http://www.thegreenpages.com.au/images/gp-dot-notfound.png";
		baseIcon2.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon2.iconSize = new GSize(29, 32);
		baseIcon2.shadowSize = new GSize(37, 34);
		baseIcon2.iconAnchor = new GPoint(9, 34);
		baseIcon2.infoWindowAnchor = new GPoint(9, 2);
		baseIcon2.infoShadowAnchor = new GPoint(18, 25);

		markerOptions = { icon:baseIcon2 };
	
		var marker = new GMarker(point, markerOptions);
		
		//	var marker2 = new Gmarker(point, markerOptions);
		var baddress = place.address
		var branchadd= baddress.split(",")
		
		
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml("<b>Company Name:</b><br /><span style=\"font-size: 14px; color: #5fa841;\">" +  branchName +"</span><br /><br />Exact location not found<br /><b>Address:</b><br />" + branchadd[0] + "<br />" + branchadd[1] );
			map.setZoom(16);
		}); 
	
	return marker;
}
	
function addAddressToMapNotFound(response) {
      // do not clear previously add markers
	  //map.clearOverlays();

      if (!response || response.Status.code != 200) {
		//alert ("not FOUND NOT FOUND AGAIN!");
	  
	  } else {
		//alert ("come over here");
        place = response.Placemark[0];
		
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);

		bounds.extend(point);
		//alert("address not found" + gcounter);
		
		map.addOverlay(createMarkerNotFound(point, place, branchName[gcounter]));	

		
		map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));	
		
	}
}
	
	
	
function addAddressToMap(response) {
      // do not clear previously add markers
	  //map.clearOverlays();
	  
	  
      if (!response || response.Status.code != 200) {
	     //place = response.Placemark[0];
		//alert("Sorry, we were unable to geocode that address Company name " + branchName[gcounter] + "the addArray is" + addArray[gcounter]);
		
		var secondtry =  addArray[gcounter];	
		addNotFound[nfcount]  = secondtry; 
		//alert("ADDNOTFOUND lets try the fixed address is instead " + secondtry );	
		
		 gcounter++;
		//geocoder.getLocations(secondtry, addAddressToMapNotFound);
	
      } else {
        place = response.Placemark[0];
		
		
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);

		//marker = new GMarker(point, markerOptions);
        //marker.openInfoWindowHtml(place.address + '<br>' +
          //'<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
		
		//	alert("Gcounter" + branchName[gcounter]);
	    
		//alert("extending the point" + point); 
		bounds.extend(point);

		map.addOverlay(createMarker(point, place, branchName[gcounter]));	
	    gcounter++;
		map.setCenter(point, 16);
		//map.showMapBlowup(point);
		//alert("setting that zoom level");
		map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));		
	}
}

    // showLocation() is called when you click on the Search button 
    // in the form.  It geocodes the address entered into the form
    // and adds a marker to the map at that location.
function showLocation() {
    var address = document.forms[0].q.value;
	  // ok check if the address is the right one..
	geocoder.getLocations(address, addAddressToMap);
}


   // findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
      document.forms[0].q.value = address;
      showLocation();
}
	
function showAllLocation(elements) {
	var address;
	
		// For each location... lets populate them together...
		// Also get the branch name...
		for ( var e = 0; e < elements.length; e++ )
		{
			address = elements[e] ;
			//geocoder.getLocations(address, addAddressToMap);
			//document.write(" Loop iteration :" + e );
			addArray[e] = elements[e].firstChild.nodeValue;
			stringadd = AddA[e] + " " + elements[e].firstChild.nodeValue;
			
			geocoder.getLocations(stringadd, addAddressToMap);
			//document.write ( "<br />" );
		} 
		
		locationCount = e;
	//	alert("Total point in the map" + locationCount);
	//	alert("addNotFound length" + addNotFound.length);
		
		/*
		for ( var e = 0; e < addNotFound.length; e++ )
		{
		
			stringadd = addNotFound[e];
			//alert ("adding not found address to the map" + stringadd );
			geocoder.getLocations(stringadd, addAddressToMapNotFound);			
			//document.write ( "<br />" );
		} 
		*/

} 
	
function getElementsByStyleClass (className) {
  var all = document.all ? document.all :
    document.getElementsByTagName('*');
  var elements = new Array();
  for (var e = 0; e < all.length; e++)
  if (all[e].className == className)
      elements[elements.length] = all[e];
  return elements;
}

function populateBranchName() {
  //alert("Populating branch name");
	branchName = new Array(getElementsByStyleClass('adName').length);

	for( i = 0 ; i < getElementsByStyleClass('adName').length; i++)
	{
		branchName[i] = getElementsByStyleClass('adName')[i].firstChild.nodeValue;
	}
	
}

function populateAddressA() {

	AddA = new Array(getElementsByStyleClass('adAddressA').length);

	for( i = 0 ; i < getElementsByStyleClass('adAddressA').length; i++)
	{
		AddA[i] = getElementsByStyleClass('adAddressA')[i].firstChild.nodeValue;
	}

}


/*
function setProperZoom() {
	// if there is only one location then zoom it in to that place
	if ( locationCount == 1 )
	{  
	//don't do anything
	// it does it when add location
	}
	else
	{
	// if there is more then one than set the appropriate zoom level..
	//set the center, and fix the zoom
		//alert(bounds.getCenter());
		
		
		//map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
	}
}
*/