var spottings = {};
var species = [];
var markers = [];
var markerClusterer;



    function load() {
      var map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(-30, 135), 5); //south australia
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());


GDownloadUrl("static/eighthfrogdata.xml", function(data, responseCode) {
  // To ensure against HTTP errors that result in null or bad data,
  // always check status code is equal to 200 before processing the data
  if(responseCode == 200) {
    var xml = GXml.parse(data);
    var markertags = xml.documentElement.getElementsByTagName("marker");
    var speciesCounter = -1;
    var colour = "";
    for (var i = 0; i < markertags.length; i++) {
          var name = markertags[i].getAttribute("name");
          var specy = markertags[i].getAttribute("type");
          var latlng = new GLatLng(parseFloat(markertags[i].getAttribute("lat")),
                              parseFloat(markertags[i].getAttribute("lng")));
          var spotting = {latlng: latlng, name: name, specy: specy};
          if (!spottings[specy]) { 
	      speciesCounter++;
              spottings[specy] = [];
              species.push(specy);
	      var check = createCheck("species-" + speciesCounter, function (evt) { toggleSpecies(evt.currentTarget.id); }, true); 
	      var label = createText(specy);
	      addRow(check,label);
	      addSpeciesImage(specy);
	      // these kind of rely on the same-species entries being adjacent...
              colour = specyToColour(speciesCounter);
          } 
	  var thismarker = createMarker(spotting,colour);
          spottings[specy].push(thismarker);
          markers.push(thismarker);

    }
    var addbutton = createButton("addbutton",addAllSpecies,"Add all"); 
    var rmbutton = createButton("removebutton",removeAllSpecies,"Remove all"); 
    addRow(addbutton, rmbutton);
    markerClusterer = new MarkerClusterer(map, markers, {maxZoom: 10} );

  } else if(responseCode == -1) {
    alert("Data request timed out. Please try later.");
  } else { 
    alert("Request resulted in error. Check XML file is retrievable.");
  }
});
}

function toggleSpecies(id) {
    var check = document.getElementById(id);
    var i = id.split('-')[1];
    var specy = species[i];
    var spots = spottings[specy];
    if (check.checked) {
	markerClusterer.addMarkers(spots);
    } else {
	// no bulk remove?
	for (var j in spots) {
	    markerClusterer.removeMarker(spots[j]);
	}
    }
}


function addAllSpecies() { 
    makeAllChecked(true);
    markerClusterer.clearMarkers();
    markerClusterer.addMarkers(markers);
}

function removeAllSpecies() { 
    makeAllChecked(false);
    markerClusterer.clearMarkers();
}


function makeAllChecked(value) {
    specieslist = document.getElementById("specieslist");
    var checks = specieslist.getElementsByTagName("input");
    for (var i in checks) {
        check = checks[i];
	if (check.type == "checkbox") {
	    var newCheck = createCheck(check.id, check.onclick,value);
	    var parent = check.parentNode;
	    parent.replaceChild(newCheck, check);
        }
    }
}




  function createButton(id, onclick, value) {
    var input = document.createElement("input");
    input.type = "submit";
    input.id = id;
    input.onclick = onclick;
    input.value = value;
    return input;
  }

  function createCheck(id, onclick, checked) {
    var input = document.createElement("input");
    input.type = "checkbox";
    input.id = id;
    input.onclick = onclick;
    input.checked = checked;
    return input;
  }  

  function createText(text) {
    var result = document.createTextNode(text);
    return result;
  }


function addSpeciesImage(specy) {
    getFlickrImage(specy);
}

  function addRow(first, second){
    var tbody = document.getElementById("specieslist").getElementsByTagName("TBODY")[0];
    var row = document.createElement("TR");
    var td1 = document.createElement("TD");
    td1.align = "right";
    td1.appendChild(first);
    var td2 = document.createElement("TD");
    td2.appendChild (second);
    row.appendChild(td1);
    row.appendChild(td2);
    tbody.appendChild(row);
  }


    function specyToColour(specy) {
        var colours = new Array("#00FFFF", "#808080", 	
 	                        "#000080", 	
                         	"#C0C0C0","#000000", 	
                         	"#008000","#808000", 	
                         	"#008080","#0000FF", 	
                         	"#00FF00","#800080", 	
                         	"#FFFFFF","#FF00FF", 	
                         	"#800000","#FF0000", 	
                         	"#FFFF00","#7FFF00",
                         	"#98FB98","#3CB371",
                         	"#006400","#556B2F",
                         	"#008B8B","#FFF8DC",
                        	"#FFEBCD","#FFE4C4",
                        	"#FFDEAD","#F5DEB3",
                        	"#DEB887","#D2B48C",
                        	"#BC8F8F","#F4A460",
                        	"#DAA520","#B8860B",
                        	"#CD853F","#D2691E",
                        	"#8B4513","#A0522D",
                        	"#A52A2A","#800000");
        return colours[specy];
//        return "#00ff00";

}


function createMarker(spotting,colour) {
      var newIcon = MapIconMaker.createMarkerIcon({width: 32, height: 32, primaryColor: colour});
      var marker = new GMarker(spotting.latlng, {icon: newIcon});
      GEvent.addListener(marker, 'click', function() {
	      var words = spotting.specy.split(' ');
	      var url = "http://frogs.org.au/frogs/species/" + words[0] + "/" + words[1] + "/";
	      var html = '<b>' + spotting.name + '</b><br/><a href="' + url + '">' + spotting.specy + "</a><br/>" ;//+ imagehtml;
	      marker.openInfoWindowHtml(html + $('#' + specyToID(spotting.specy)).html() );
      });
      return marker;
}


function specyToID(specy) {
    return specy.replace(" ","-").replace(".","");
}


function getFlickrImage(specy) {
    var id = specyToID(specy);
    var html = '<div id="' + id + '"></div>';  //holder for flickr image;
    $("#speciesimages").append(html);
    $("#" + id).hide();
    $.getJSON(
		"http://api.flickr.com/services/rest/?jsoncallback=?",
		{ method : "flickr.photos.search",
			api_key : "3e9dfdcc79141d517352d8deb8b81b12",
			format : "json",
			text : specy,
			sort : "relevance",
			per_page: 1
			},
		callbackwrapper(specy, id)
    );
}


function callbackwrapper(specy, id) {
 return function( data, status) {
    var small_url = "";
    var photo_url = "";
    $.each(data.photos.photo, function(photoIdx, photo) {
	    // Build the thumbnail url
	    small_url = ["http://farm", photo.farm, ".static.flickr.com/", 
			photo.server, "/", photo.id, "_", photo.secret, "_s.jpg"].join("");
	    // Build the photo url
	    photo_url = ["http://www.flickr.com/photos/", 
			photo.owner, "/", photo.id].join("");
	});
    imagehtml = '<a href="' + photo_url + '" target="_blank"><img src="' + small_url + '" width=75 height=75 border=0 /></a>'; 
    $('#' + id).append(imagehtml);
  }
}

