// JavaScript Document

var xmlHTTP;
	function createXMLHttpRequest(){
		if(window.ActiveXObject){
			xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
		}else if(window.XMLHttpRequest){
			xmlHTTP = new XMLHttpRequest();
		}
	}


var map;
var gdir;
var latlng2;
function initialize() {
  if (GBrowserIsCompatible()) { 
   map = new GMap2(document.getElementById("map_canvas"));
    gdir = new GDirections(map, document.getElementById("directions"));
	map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl());
    GEvent.addListener(gdir, "error", handleErrors);
    GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); // Triggers marker swap, Esa
    map.setCenter(new GLatLng(0,0),0);	// inital setCenter()  added by Esa.
    getMethode();
    // api version display added by Esa
    //document.getElementById("api-v").innerHTML = '2.'+G_API_VERSION;
  }
}
function getMethode(){
	var end = new Date();
	var from = document.getElementById("fromAddress");
	var to = document.getElementById("myInput");
	var locale =  document.getElementById("locale");
	var url = "ajaxGetToLatLng.php?str="+to.value+","+from.value+"&ts="+end.getTime();
	//alert(from.value);
	
	if(to.value == 'Business Name' || to.value == ''){
		alert("Please select your detination!");
		to.focus();
	}
	
	if(from.value == 'Business Name' || to.value == 'Business Name' || from.value == '' || to.value == ''){
		setDirections("PA TONG, phuket","rawai ,phuket","en");
	}else{
		createXMLHttpRequest();
		xmlHTTP.onreadystatechange = handleStateChange;
		xmlHTTP.open("GET",url,true);
		xmlHTTP.send(null);
		return false;
	}
}
function handleStateChange(){
	if(xmlHTTP.readyState == 4){
		if(xmlHTTP.status == 200){
				var from = document.getElementById("fromAddress");
				var to = document.getElementById("myInput");
				var locale =  document.getElementById("locale");
				latlng2 = xmlHTTP.responseText;
				if(xmlHTTP.responseText != ","){
					p = xmlHTTP.responseText.split("|");
					//alert(p[0]);
					 setDirections(p[0],p[1],locale.value);
				}else{					
					setDirections(from.value,"rawai ,phuket",locale.value);
				}
			}
		}
	}

function setDirections(fromAddress, toAddress, locale) {
//alert("From : "+fromAddress+" To : "+toAddress)
//alert(fromAddress);
  gdir.load("from: " + fromAddress + " to: " + toAddress,
  { "locale": locale , "getSteps":true});
}

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_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.");
}
  
///////////////////////////////////////////////////////////////////////

/**
* The add-on code for draggable markers
* @author Esa 2008
*/
var newMarkers = [];
var latLngs = [];
var icons = [];

// Note the 'addoverlay' GEvent listener inside initialize() function of the original code (above).
// 'load' event cannot be used

function onGDirectionsAddOverlay(){ 
  // Remove the draggable markers from previous function call.
  for (var i=0; i<newMarkers.length; i++){
    map.removeOverlay(newMarkers[i]);
  }

  // Loop through the markers and create draggable copies
  for (var i=0; i<=gdir.getNumRoutes(); i++){
    var originalMarker = gdir.getMarker(i);
    latLngs[i] = originalMarker.getLatLng();
    icons[i] = originalMarker.getIcon();
    newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:'Draggable'});
    map.addOverlay(newMarkers[i]);
	//alert(latLngs[i]);
    // Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
    GEvent.addListener(newMarkers[i], "dragend", function(){
      var points = [];
      for (var i=0; i<newMarkers.length; i++){
        points[i]= newMarkers[i].getLatLng();
      }
	  //alert(points);
      gdir.loadFromWaypoints(points);
    });

    //Bind 'click' event to original markers 'click' event
    copyClick(newMarkers[i],originalMarker);

    // Now we can remove the original marker safely
    map.removeOverlay(originalMarker);
	//onGDirectionsLoad();
  }

  function copyClick(newMarker,oldMarker){
    GEvent.addListener(newMarker, 'click', function(){
      GEvent.trigger(oldMarker,'click');
    });
  }
}

// For Printing Direction 
 function onGDirectionsLoad(){ 
   var poly = gdir.getPolyline();
   if (poly.getVertexCount() > 500) {
	  document.getElementById("staticMapOverviewIMG").innerHTML = "This route has too many vertices";
    // alert("This route has too many vertices");
     return;
   }
   var baseUrl = "http://maps.google.com/staticmap?";

   var params = [];
   var markersArray = [];
   markersArray.push(poly.getVertex(0).toUrlValue(5) + ",greena");
   markersArray.push(poly.getVertex(poly.getVertexCount()-1).toUrlValue(5) + ",greenb");
   params.push("markers=" + markersArray.join("|"));

   var polyParams = "rgba:0x0000FF80,weight:5|";
   var polyLatLngs = [];
   for (var j = 0; j < poly.getVertexCount(); j++) {
     polyLatLngs.push(poly.getVertex(j).lat().toFixed(5) + "," + poly.getVertex(j).lng().toFixed(5));
   }
   params.push("path=" + polyParams + polyLatLngs.join("|"));
   params.push("size=500x500");
   params.push("key=ABQIAAAAm5b3C5AbQqmB3hCj2ksQhhSQXcMvq9o7AK-Nz0R354QDb7w_WhSYguqk0ScoXNhjNqPD2iTGU_3yJg");

   baseUrl += params.join("&");

   var extraParams = [];
   extraParams.push("center=" + map.getCenter().lat().toFixed(6) + "," + map.getCenter().lng().toFixed(6));
   extraParams.push("zoom=" + map.getZoom());
   addImg(baseUrl + "&" + extraParams.join("&"), "staticMapOverviewIMG");

   var extraParams = [];
   extraParams.push("center=" + poly.getVertex(0).toUrlValue(5));
   extraParams.push("zoom=" + 15);
   addImg(baseUrl + "&" + extraParams.join("&"), "staticMapStartIMG");

   var extraParams = [];
   extraParams.push("center=" + poly.getVertex(poly.getVertexCount()-1).toUrlValue(5));
   extraParams.push("zoom=" + 15);
   addImg(baseUrl + "&" + extraParams.join("&"), "staticMapEndIMG");
}

function addImg(url, id) {
 var img = document.createElement("img");
 img.src = url;
 document.getElementById(id).innerHTML = "";
 document.getElementById(id).appendChild(img);
}
