var side_bar_html = "";
var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var map;
var gdir;
var reasons=[];
    reasons[200] = "Success";
    reasons[601]    = "Missing Address.";
    reasons[602]    = "Unknown Address.";
    reasons[603]= "Unavailable Address.";
    reasons[610] = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[620]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[500]    = "Server error: The geocoding request could not be successfully processed.";
    reasons[400]     = "A directions request could not be successfully parsed.";
    reasons[601]   = "No query was specified in the input.";
    reasons[604] = "Unable to find a route between the two addresses.";
var error = 0;

$(document).ready(function(){

	// Accordion
	$("#accordion").accordion({ header: "h3", fillSpace: true,  event: 'mouseover'});
	$("#accordion H3 A").click(function(){return false});
	$('#buildings_link').click(function(){
		$("#accordion").accordion('activate',0);
		return false;
	});
	
	$(window).unload( function () { GUnload(); } );
	
	if (GBrowserIsCompatible()) {

    // create the map
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(40.739202, -74.042133), 14);
    map.savePosition();
  
    // === create a GDirections Object ===
    gdir=new GDirections(map);

    // === catch Directions errors ===
    GEvent.addListener(gdir, "error", function() {
      var code = gdir.getStatus().code;
      var reason="Error (code: "+code+")";
      var msg;
      if (code == 500 && error < 10)
      {
      	error++;
      	getDirections(); //Retry
      }
      else
      {
      	error = 0;
        if (reasons[code]) {
          reason = reasons[code]; 
        } 
        alert(reason);
      }
    });
    
    GEvent.addListener(gdir, "load", function() {
    //  if (gdir.getStatus().code == 'G_GEO_SUCCESS')
      {
      	error = 0;
        $('#directions').html('<p>'+ gdir.getSummaryHtml() +'</p>');
        
        $("#accordion").accordion('activate',2);
        $('#directions_msg').remove();
        for (var i in gmarkers.length)
        {
          gmarkers[i].closeInfoWindow();
        }
        //Style
        $('#directions TABLE').css('background-color','black');
      }
    });
  
    loadMarkers();
  }
  else {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  }


});


function loadMarkers() {
	var request = GXmlHttp.create();
  request.open("GET", BASE_URL+"location/get-markers/format/xml", true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = GXml.parse(request.responseText);
      // obtain the array of markers and loop through it
      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 = markers[i].getAttribute("html");
        var label = markers[i].getAttribute("label");
        var id = markers[i].getAttribute("id");
        var building = markers[i].getAttribute("building");
        var icon = markers[i].getAttribute("icon");
        var location_type = markers[i].getAttribute("location_type");
        
        // create the marker
        createMarker(point,label,html,id, building, location_type, icon);
      }
      // put the assembled side_bar_html contents into the side_bar div
      document.getElementById("side_bar").innerHTML = side_bar_html;
      //Load default markers
      loadLocationType(0);
    }
  }
  request.send(null);
}

function loadLocationType(id)
{
	gdir.clear();
	map.returnToSavedPosition();
	map.clearOverlays()
	for (var i in locationTypes)
	{
	   $('#location_type_'+i).removeClass('selected');
	}
	for (var i in locationTypes[id])
	{
		map.addOverlay(gmarkers[locationTypes[id][i]]);
	}
	if (id != 0)
	{
		$('#location_type_'+id).addClass('selected');
		for (var i in locationTypes[0])
    {
      map.addOverlay(gmarkers[locationTypes[0][i]]);
    }
	}
}
// A function to create the marker and set up the event window
function createMarker(point,name,html, id, building, location_type, icon_color) {
	
	var icon = new GIcon();
  icon.image = BASE_URL+'scripts/mapfiles/'+icon_color+'/markers/image.png';
  icon.shadow = BASE_URL+'scripts/mapfiles/'+icon_color+'/markers/shadow.png';
  icon.iconSize = new GSize(32,32);
  icon.shadowSize = new GSize(48,32);
  icon.iconAnchor = new GPoint(16,32);
  icon.infoWindowAnchor = new GPoint(16,0);
  icon.printImage = BASE_URL+'scripts/mapfiles/'+icon_color+'/markers/printImage.gif';
  icon.mozPrintImage = BASE_URL+'scripts/mapfiles/'+icon_color+'/markers/mozPrintImage.gif';
  icon.printShadow = BASE_URL+'scripts/mapfiles/'+icon_color+'/markers/printShadow.gif';
  icon.transparent = BASE_URL+'scripts/mapfiles/'+icon_color+'/markers/transparent.png';
  icon.imageMap = [19,0,20,1,21,2,22,3,23,4,24,5,24,6,24,7,24,8,24,9,24,10,24,11,24,12,23,13,23,14,22,15,21,16,20,17,20,18,19,19,19,20,18,21,18,22,17,23,17,24,17,25,17,26,16,27,16,28,16,29,16,30,16,31,14,31,14,30,14,29,14,28,14,27,14,26,13,25,13,24,13,23,12,22,12,21,12,20,11,19,10,18,10,17,9,16,8,15,7,14,7,13,6,12,6,11,6,10,6,9,6,8,6,7,6,6,7,5,7,4,8,3,9,2,10,1,11,0];
  

  var marker = new GMarker(point, {"icon":icon});

  //var id = gmarkers.length;
  if (building == 1)
  {
    // The info window version with the "to here" form open
    to_htmls[id] = html + '<br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + id + ')">From here<\/a>' +
       '<br>Start address:<form action="javascript:getDirections()">' +
       '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
       '<INPUT value="Get Directions" TYPE="SUBMIT"><br>' +
       'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
       '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + 
       '"/>';
    // The info window version with the "from here" form open
    from_htmls[id] = html + '<br>Directions: <a href="javascript:tohere(' + id + ')">To here<\/a> - <b>From here<\/b>' +
       '<br>End address:<form action="javascript:getDirections()">' +
       '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
       '<INPUT value="Get Directions" TYPE="SUBMIT"><br>' +
       'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
       '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
       '"/>';
    // The inactive version of the direction info
    html = html + '<br>Directions: <a href="javascript:tohere('+id+')">To here<\/a> - <a href="javascript:fromhere('+id+')">From here<\/a>';
    
    side_bar_html += '<p><a href="javascript:myclick(' + id + ')">' + name + '<\/a></p>';
  }

 	GEvent.addListener(marker, "mouseover", function() {
    marker.openInfoWindowHtml(html);
  });
  
  gmarkers[id] = marker;
  locationTypes[location_type].push(id);
  htmls[id] = html;
  
  
  //return marker;
}

// ===== request the directions =====
function getDirections() {
  // ==== Set up the walk and avoid highways options ====
  var opts = {};
  if (document.getElementById("walk").checked) {
     opts.travelMode = G_TRAVEL_MODE_WALKING;
  }
  if (document.getElementById("highways").checked) {
     opts.avoidHighways = true;
  }
  // ==== set the start and end locations ====
  var saddr = document.getElementById("saddr").value
  var daddr = document.getElementById("daddr").value
  gdir.load("from: "+saddr+" to: "+daddr, opts);
  
}


// This function picks up the click and opens the corresponding info window
function myclick(id) {
  gmarkers[id].openInfoWindowHtml(htmls[id]);
}

// functions that open the directions forms
function tohere(id) {
  gmarkers[id].openInfoWindowHtml(to_htmls[id]);
}
function fromhere(id) {
  gmarkers[id].openInfoWindowHtml(from_htmls[id]);
}

  // This Javascript is based on code provided by the
  // Blackpool Community Church Javascript Team
  // http://www.commchurch.freeserve.co.uk/   
  // http://econym.googlepages.com/index.htm
