var map;

function Locations(state, suburb, postcode) {
	this.state = state;
	this.suburb = suburb;
	this.postcode = postcode;
}

function initialize() {
	
  map = new GMap2(document.getElementById("map_canvas"));
  map.addControl(new GLargeMapControl());
	geocoder = new GClientGeocoder();
	if (document.forms[0].state.value==null || document.forms[0].state.value=="") {
 	 	getMerchantLocations("maps/all.xml");
  	changeState("maps/all.xml");
  	
	} else {
		//getMerchantLocations("maps/" + document.forms[0].state.value + "/all.xml");
  	changeState("maps/" + document.forms[0].state.value + "/all.xml");
  	getMerchantLocations("maps/all.xml");
  }
}

function initialize_venue() {
  var info_window_showing = false;
  map = new GMap2(document.getElementById("map_canvas"));
  map.addControl(new GLargeMapControl());
  if (document.form3.nlat.value==0.0&&document.form3.nlon.value==0.0)
  	map.setCenter(new GLatLng(-35.283462,149.152794), 8);
  else {
  	var pt = new GLatLng(document.form3.nlat.value,document.form3.nlon.value)
  	map.setCenter(pt, 12);
  	map.addOverlay(createMarker2(pt));
  }
  geocoder = new GClientGeocoder();
  //document.forms[0].latlng.disabled = true;
}



function getMerchantLocations(locationFile) {

  var request = GXmlHttp.create();
  request.open("GET", locationFile, true);
  request.onreadystatechange = function() {

    if (request.readyState == 4) {

      var xmlDoc = GXml.parse(request.responseText);

      var mapWindow = xmlDoc.documentElement;
      var lat = mapWindow.getAttribute("lat");
      var lng = mapWindow.getAttribute("lng");
      var zoom = mapWindow.getAttribute("zoom");

      map.setCenter(new GLatLng(lat, lng), parseInt(zoom));

      var markers = xmlDoc.documentElement.getElementsByTagName("marker");
  		
      for (var i = 0; i < markers.length; i++) {
	// obtain the attribues of each marker
	var lat = parseFloat(markers[i].getAttribute("lat"));
	var lng = parseFloat(markers[i].getAttribute("lng"));
	var point = new GLatLng(lat,lng);
	var html = GXml.value(markers[i]);
	var label = markers[i].getAttribute("label");

      
      //alert(locCounter);
	// create the marker
	var marker = createMarker(point,label,html);
	map.addOverlay(marker);
      }
      
    }
  }

  request.send(null);
}

// 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, name, html) {
  
  var marker = new GMarker(point);
  
  GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(html);
    });
  
  GEvent.addListener(marker, "infowindowopen", function() {
      info_window_showing = true;
    });
  
  GEvent.addListener(marker, "infowindowclose", function() {
      info_window_showing = false;
    });
  
  return marker;
  
}

function populateSuburb(state, loc, options) {
	
	var optionCounter = 0;
    	var suburbExists = false;  
    	var tmpSubList = new Array(); 
    	var tmpSubPostList = new Array(); 	
      for (i=0; i<loc.length; i++) {
      	//alert(loc[i].suburb);
      	
      	if (loc[i].state == state) {
      			for (j=0; j<i; j++) {
      				if (loc[i].suburb == loc[j].suburb) {
      					suburbExists = true;
      				}
      			}
      			
      			if (!suburbExists) {
      				//options[optionCounter] = new Option(loc[i].suburb, loc[i].suburb + " " + loc[i].postcode);
      				tmpSubList[optionCounter] = loc[i].suburb;
      				tmpSubPostList[optionCounter] = loc[i].suburb + " " + loc[i].postcode;
      				optionCounter++;
      				
      			}
      			suburbExists = false;
      	}
      }
      
      tmpSubList.sort();
      tmpSubPostList.sort();
      
      for (j=0; j<optionCounter; j++){
      	options[j+1] = new Option(tmpSubList[j], tmpSubPostList[j]);
      }
}

function changeState(locationFile) {
	var request2 = GXmlHttp.create();
  request2.open("GET", locationFile, true);
  request2.onreadystatechange = function() {
	
	
	var loc = new Array();
  var locCounter = 0;

   if (request2.readyState == 4) {

      var xmlDoc = GXml.parse(request2.responseText);
      var states = xmlDoc.documentElement.getElementsByTagName("state");
  		
        
  stateIndex = document.forms[0].state.selectedIndex;
	
  with(document.forms[0].suburb) {
    options.length=0;

    if (stateIndex == 0){
      options[0] = new Option("Select a state...", "");
    } else {
      options[0] = new Option("Select a suburb...", "");
      populateSuburb2(states, options);
    }
  
  }
}
}
request2.send(null);
}

function populateSuburb2(states, options) {
		 //alert("!!" + states.length);
		 for (var i=0; i<states.length; i++) {
		 	
		 	//alert(states.length);
     		//if (states[i].getAttribute("name")==state) {
     			var suburbs = states[i].getElementsByTagName("suburb");
     			for (var j=0; j<suburbs.length; j++) {
     				options[j+1] = new Option(suburbs[j].getAttribute("name"),suburbs[j].getAttribute("name") + " " + suburbs[j].getAttribute("postcode"));
     			}
     		//}
     	}
}

function showLocation() {

  var stateIndex  = document.forms[0].state.selectedIndex;
  var suburbIndex = document.forms[0].suburb.selectedIndex;

  var stateValue =  document.forms[0].state.options[stateIndex].value;
  var suburbValue = document.forms[0].suburb.options[suburbIndex].value;

  if (suburbValue.length > 0) {

    //getMerchantLocations("maps/" + stateValue + "/" + suburbValue + ".xml");
    
    var address = suburbValue + " " + stateValue + " Australia";
    geocoder.getLocations(address, setMapCenter);
    
  }
 }

function showLocation2() {
  var address = document.form3.nadd1.value + " " + document.form3.nadd2.value + " " + document.form3.nsuburb.value + " " + document.form3.nstate.value + " australia";
  geocoder.getLocations(address, addAddressToMap);

}
 
function addAddressToMap(response) {
   
	map.clearOverlays();
      
  if (!response || response.Status.code != 200) {
    alert("Sorry, we were unable to identify that address");
  } else {
    var place = response.Placemark[0];
    document.forms[0].latlng.value = place.Point.coordinates[1] + '/' + place.Point.coordinates[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    var marker = new GMarker(point, {draggable: true});
        
    GEvent.addListener(marker, "dragstart", function() {  
     	map.closeInfoWindow();  });
    GEvent.addListener(marker, "dragend", function() {  
     	document.forms[0].latlng.value = marker.getLatLng().lat() + '/' + marker.getLatLng().lng()});
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(place.address + '<br>' +
      '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
    });
    
    GEvent.addListener(marker, "infowindowopen", function() {
      info_window_showing = true;
    });
    
    GEvent.addListener(marker, "infowindowclose", function() {
      info_window_showing = false;
    });

    map.addOverlay(marker);
        
   }
}

function setMapCenter(response) {
   
	//map.clearOverlays();
      
  if (!response || response.Status.code != 200) {
    alert("Sorry, we were unable to identify that address");
  } else {
    var place = response.Placemark[0];
    //document.form[0].nlat.value = place.Point.coordinates[1]; 
    //document.form[0].nlon.value = place.Point.coordinates[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    var marker = new GMarker(point, {draggable: false});
        
    //GEvent.addListener(marker, "dragstart", function() {  
    // 	map.closeInfoWindow();  });
    //GEvent.addListener(marker, "dragend", function() {  
    // 	document.form3.nlat.value = marker.getLatLng().lat()
   	//	document.form3.nlon.value = marker.getLatLng().lng()});
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(place.address);
    });
    
    GEvent.addListener(marker, "infowindowopen", function() {
      info_window_showing = true;
    });
    
    GEvent.addListener(marker, "infowindowclose", function() {
      info_window_showing = false;
    });
		map.setCenter(new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]), 14);
    //map.addOverlay(marker);
        
   }
}

function createMarker2(point) {

  var marker = new GMarker(point, {draggable: true});
        
	GEvent.addListener(marker, "dragstart", function() {  
  	map.closeInfoWindow();  });
  GEvent.addListener(marker, "dragend", function() {  
   	document.form3.nlat.value = marker.getLatLng().lat()
   	document.form3.nlon.value = marker.getLatLng().lng()});
	return marker;

}

function manualMarker() {
	map.clearOverlays();
  var manualPoint = map.getCenter();
 
  document.form3.nlat.value = manualPoint.lat();
  document.form3.nlon.value = manualPoint.lng();    	
  map.addOverlay(createMarker2(manualPoint));
}



