// Dean Edwards/Matthias Miller/John Resig
var map;
var initComplete = false;

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
  initializeMap();
  initializeUI();
  
  var search_param = document.location.search;
  if (search_param == "" && document.location.pathname.indexOf("routes/") > -1)  {
    route_id = document.location.pathname.slice(document.location.pathname.indexOf("routes/")+7).split("/")[0];
    search_param = encodeURI("?route_id=" + route_id);
  }
  else if (search_param.indexOf('route_id') < 1)  {
    x = document.getElementById('posts');
    title_text = x.getElementsByTagName('h1')[0].firstChild.firstChild.nodeValue;
    //title_text = title_text.slice(0,title_text.length-22)
    if (title_text != "Ride Free Bike Map Creator" && "Members Only Map Creator")  {
      search_param = encodeURI("?route_name=" + title_text);
    }
  }
  
  if (search_param)  {
    var url = "/cgi-bin/routeaccess.py" + search_param
    url = url+"&sid="+Math.random();
    jQuery.get(url, function(data)  {
      xml_node = data;
      travel_mode = xml_node.getElementsByTagName("Data")[0].firstChild.firstChild.data;
      document.getElementById("travel_mode_select").selectedIndex = travel_mode;
      if (travel_mode)  {
	//select driving if the index is 1.
	travelMode = google.maps.DirectionsTravelMode.DRIVING;
      }

      points = xml_node.getElementsByTagName("Point");
      if (points.length)  {
	var route_bounds = new google.maps.LatLngBounds();
	for(point = 0; point < points.length; point++)  {
	  LngLat = points[point].firstChild.firstChild.nodeValue;
	  LngLat = LngLat.split(",")
	  LatLng = new google.maps.LatLng(parseFloat(LngLat[1]),parseFloat(LngLat[0]))
	  plotRoute(LatLng);
	  route_bounds.extend(LatLng);
	}
	map.fitBounds(route_bounds);
      }
      initComplete = true;
      directionsQueProcessor();
      }, "xml");
  }
  else  {
    initComplete = true;
  }
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;

