  function resize_and_recenter_map() {
    var my_saved_latlng = map.getCenter();
    var old_size = map.getSize();
    map.checkResize();
    // Hello!
    // if (!old_size.equals(map.getSize())) {
    if (!old_size.equals(map.getSize())) {
      map.setCenter(my_saved_latlng);
      if (saved_zoom) {
        map.setZoom(saved_zoom);
        saved_zoom = 0;
      }
    }
  }

  /* Work around Google Maps not liking tabs */
  $(function() {
    $('#tabbook > ul').tabs({
      show: function(ui) {
        if (ui.panel.id == 'tab-map')
          resize_and_recenter_map();
      }
    });
  });

  //<![CDATA[
  var map;
  var geocoder;
  var saved_latlng;
  var gdir;
  var useAddress = 0;
  var saved_zoom = 3;

  function findTop(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
      do {
        curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);
    }
    return curtop;
  }

  function resize_area() {
    var DebugTextArea = document.getElementById('debugtext');
    var cm_mapTR = document.getElementById('cm_mapTR');
    var sidebar = document.getElementById('sidebar');
    var tabdetails = document.getElementById('tab-details');
    var tabmap = document.getElementById('map');
    var tabdirections = document.getElementById('directions');
    var oldHeight = parseInt(cm_mapTR.style.height);
    var contentHeight = document.body.parentNode.scrollHeight;
    var innerHeight;
    var sortbydistancerow = document.getElementById('sortbydistancerow');
    var cm_map_top = findTop(cm_mapTR);
    var newHeight;
    var newHeight2;

    if( typeof( window.innerWidth ) == 'number' ) {
      //Non-IE
      innerHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
      //IE 6+ in 'standards compliant mode'
      innerHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
      //IE 4 compatible
      innerHeight = document.body.clientHeight;
    }

    DebugTextArea.innerHTML = 'window.innerheight is '+ innerHeight + '; cm_map_top is ' + cm_map_top + '; Old Height = ' + oldHeight;
    newHeight2 = (innerHeight - cm_map_top) - 50;

    newHeight = innerHeight - cm_map_top -
      (contentHeight - (cm_map_top + oldHeight));

    if (newHeight < newHeight2) {
        newHeight = newHeight2;
    }

    DebugTextArea.innerHTML = DebugTextArea.innerHTML + 'contentHeight is ' + contentHeight;
    DebugTextArea.innerHTML = DebugTextArea.innerHTML + '. Map height is ' + oldHeight + '. New height is ' + newHeight;
    if (newHeight > 20) {
      cm_mapTR.style.height = newHeight + "px";
      if (sortbydistancerow.style.display == "none")
        sidebar.style.height = newHeight - 20 + "px";
      else
        sidebar.style.height = newHeight - 50 + "px";
      tabdetails.style.height = newHeight - 50 + "px";
      tabmap.style.height = newHeight - 50 + "px";
      tabdirections.style.height = newHeight - 50 + "px";
    }
    resize_and_recenter_map();
  }

  function load() {
    if (GBrowserIsCompatible()) {
      var JavaScriptControls = document.getElementById('HaveJavaScript');
      var NoJavaScriptMessage = document.getElementById('NoJavaScript');
      JavaScriptControls.style.display = "inline";
      NoJavaScriptMessage.style.display = "none";
      geocoder = new GClientGeocoder();
      map = new GMap2(document.getElementById('map'));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.addControl(new GScaleControl());
      map.enableScrollWheelZoom();
      map.enableContinuousZoom();
      saved_latlng = new GLatLng(-25.3, 134.3);
      map.setCenter(saved_latlng, 3);
      searchLocationsNear(map.getCenter());
      resize_area();
      map.setMapType(G_HYBRID_MAP);
      gdir = new GDirections(map, document.getElementById("directions"));
      GEvent.addListener(gdir, "error", handleErrors);
    } else {
      var NoJavaScriptMessage = document.getElementById('NoJavaScript');
      NoJavaScriptMessage.innerHTML = 'Sorry. Your browser is not GoogleMaps compatible. You will be able to view congregation details, but not maps or driving directions.';
    }
  }

  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.\nYou might also try adding the state and/or country, as Google sometimes matches less specific addresses with American locations.\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.\nError code:" + gdir.getStatus().code);
	   
  }

  function no_search_by_address() {
    var sortbydistancecheckbox = document.getElementById('sortbydistancecheckbox');
    var sortbydistancerow = document.getElementById('sortbydistancerow');

    sortbydistancecheckbox.checked = 0;
    gdir.clear();
    sortbydistancerow.style.display = "none";
    useAddress = 0;
    searchLocationsNear(saved_latlng);
    $('#tabbook > ul').tabs('disable', 2);
  }

  function searchLocations() {
    var address = document.getElementById('addressInput').value;
    var sortbydistancerow = document.getElementById('sortbydistancerow');

    if (!address.length)
      no_search_by_address();
    else {
      geocoder.getLatLng(address + ', Australia', function(latlng) {
        if (latlng) {
          saved_latlng = latlng;
          try {
            sortbydistancerow.style.display="table-cell";
          } catch(err) {
            sortbydistancerow.style.display="block";
          }
          useAddress = 1;
          $('#tabbook > ul').tabs('enable', 2);
          searchLocationsNear(latlng);
        } else
          no_search_by_address();
        resize_area();
      });
    }
  }

  function SelectState() {
    saved_zoom = 0;
    searchLocationsNear(saved_latlng);
  }

  function searchLocationsNear(center) {
    var region = document.getElementById('regionSelect').value;
    var searchUrl = '/sites/default/plugins/phpsqlsearch_genxml.php';
    var haveCriteria = 0;
    var sortbydistancecheckbox = document.getElementById('sortbydistancecheckbox');

    if (useAddress) {
      searchUrl = searchUrl + '?lat=' + center.lat() + '&lng=' + center.lng();
      haveCriteria = 1;
    }

    if (region.length) {
      if (!haveCriteria)
        searchUrl = searchUrl + '?region=' + region;
      else
        searchUrl = searchUrl + '&region=' + region;
    }

    if (sortbydistancecheckbox.checked) {
      if (!haveCriteria)
        searchUrl = searchUrl + '?distancesort=1';
      else
        searchUrl = searchUrl + '&distancesort=1';
    }

    GDownloadUrl(searchUrl, function(data) {
      var xml = GXml.parse(data);
      var markers = xml.documentElement.getElementsByTagName('marker');
      map.clearOverlays();

      var sidebar = document.getElementById('sidebar');
      sidebar.innerHTML = '';
      if (markers.length == 0) {
        sidebar.innerHTML = 'No results found.';
        map.setCenter(new GLatLng(-25.3, 134.3), 3);
        return;
      }

      var bounds = new GLatLngBounds();
      for (var i = 0; i < markers.length; i++) {
        var name = markers[i].getAttribute('name');
        var address = markers[i].getAttribute('address');
        var tip = markers[i].getAttribute('tip');
        var DirectionDescription = markers[i].getAttribute('DirectionDescription');
        var distance = parseFloat(markers[i].getAttribute('distance'));
        var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                parseFloat(markers[i].getAttribute('lng')));
         
        var marker = createMarker(point, name, DirectionDescription, tip);
        map.addOverlay(marker);
        var sidebarEntry = createSidebarEntry(marker, name, address, distance);
        sidebar.appendChild(sidebarEntry);
        bounds.extend(point);
      }
      map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    });
  }

  function createMarker(point, name, DirectionDescription, tip) {
    var marker = new GMarker(point, {title:name});
    var html = '<h1><strong>' + name + '</strong></h1><br/>' + tip;
    GEvent.addListener(marker, 'click', function() {
      var from_address = document.getElementById('addressInput').value;
      if (from_address.length > 0) {
        gdir.load("from: " + from_address + ", Australia to: " + DirectionDescription,
              { "locale" : "en" } );
      } else {
        gdir.clear();
        if (map.getZoom() < 12)
          map.setZoom(14);

        saved_latlng = marker.getLatLng();
        map.setCenter(saved_latlng);
      }
      document.getElementById('congregation_details').innerHTML= html;
      saved_zoom = 0;
    });
    return marker;
  }

  function createSidebarEntry(marker, name, address, distance) {
    var div = document.createElement('div');
    var html = '<strong>' + name + '</strong>';
    if (distance)
      html = html + ' (' + distance.toFixed(1) + 'km)';
    html = html + '<br/>' + address
    div.innerHTML = html;
    div.style.cursor = 'pointer';
    div.style.marginBottom = '5px'; 
    GEvent.addDomListener(div, 'click', function() {
      GEvent.trigger(marker, 'click');
      var from_address = document.getElementById('addressInput').value;
      if (from_address.length == 0) {
        saved_latlng = marker.getLatLng();
        map.setCenter(saved_latlng);
      }
    });
    GEvent.addDomListener(div, 'mouseover', function() {
      div.style.border = '1px solid red';
    });
    GEvent.addDomListener(div, 'mouseout', function() {
      div.style.border = '0px';
    });
    return div;
  }

  window.onload = function() {
    load();
  }

  window.onunload = function() {
    GUnload();
  } 

  window.onresize = function() {
    resize_area();
  } 

