if (GBrowserIsCompatible()) {

// Define the global variables.
var Records;          // The IMMA records
var om;               // Overlay message
var allmarkers = [];  // Index them by record number
var mm;               // Marker manager
var lastSelected;     // Currently selected record
var boxH;             // Marker array for setZoom
var selectedZIndex=1000000000; // Force selected marker on top

// use 20mm icons
var icon = new GIcon();
icon.image      = "http://labs.google.com/ridefinder/images/mm_20_red.png";
icon.shadow     = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.iconSize         = new GSize(12, 20);
icon.shadowSize       = new GSize(22, 20);
icon.iconAnchor       = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);      
// Different colour icons for the three different position sources
var gicons = [];
gicons["1"]  = new GIcon(icon,"http://labs.google.com/ridefinder/images/mm_20_red.png");
gicons["2"]  = new GIcon(icon,"http://labs.google.com/ridefinder/images/mm_20_green.png");
gicons["3"]  = new GIcon(icon,"http://labs.google.com/ridefinder/images/mm_20_blue.png");
gicons["4"]  = new GIcon(icon,"http://labs.google.com/ridefinder/images/mm_20_orange.png");
gicons["5"]  = new GIcon(icon,"http://labs.google.com/ridefinder/images/mm_20_brown.png");
gicons["6"]  = new GIcon(icon,"http://labs.google.com/ridefinder/images/mm_20_purple.png");
gicons["7"]  = new GIcon(icon,"http://labs.google.com/ridefinder/images/mm_20_gray.png");
// Yellow for currently selected
gicons["0"]  = new GIcon(icon,"http://labs.google.com/ridefinder/images/mm_20_yellow.png");


// Load the data from a file
function loadData(source_url,title) {

   // Throw up a loading message
    om = new OverlayMessage(document.getElementById('map_div'));      
    om.Set("<b>Loading "+title+" ...</b>");
    
  // Clean out any existing data
    if(mm) {
        mm.clearMarkers();
    }
    else {
        mm = new MarkerManager(map,{trackMarkers: true});
    }
    //map.clearOverlays();
    for (var i=0;i<allmarkers.length;i++) {
    	if(allmarkers[i]!=null) { map.removeOverlay(allmarkers[i]); }
    }
    Records = new Array();
	lastSelected=null;
	allmarkers = [];
	boxH = [];
      
  // Set the title
	var pTmp = document.createTextNode(title);
	document.getElementById("title_string").firstChild.removeChild(
	            document.getElementById("title_string").firstChild.firstChild);
	document.getElementById("title_string").firstChild.appendChild(pTmp);
    
  // Load the data
    GDownloadUrl(source_url, processIMMA);
}

// Process the IMMA file when its loaded
function processIMMA(doc) {
  var Acc_html = "";    // HTML for text representations
  lines = doc.split("\n");
  for (var i=0; i<lines.length; i++) {
      Records.push(new IMMA(lines[i]));
 	  Acc_html+="<p class=\"record\" "+
                "id=\"record_p"+i+"\"><tt>"+
                Records[i].string+"</tt></p>";
     // Make a marker for the record           
      allmarkers[i] = makeMarker(i,false);
     // Add it to the manager
	  if(allmarkers[i]!=null) {
          mm.addMarker(allmarkers[i],zoomLevel(i),17);
	  }
  }
 // Add the text representations to the document
  document.getElementById("record_div").innerHTML = Acc_html;
 // Add the selection callbacks to the record lines
  for (var i=0; i<lines.length; i++) {
  	listenIMMA(i)
  }
 // Add the markers to the map 
  mm.refresh();
 // Clear the loading message
  om.Clear();
}
          
// Callback for clicks on an IMMA line
function listenIMMA(i) {
    GEvent.addDomListener(document.getElementById("record_p"+i),"click",
       function() { 
	     setSelected(i);
       });
}

// Selected markers need a big z-index
function bigZIndex(marker,b) {
        return selectedZIndex++;
}
// Allways use the same icon by default
// Override setIcon for varying colors
function setIcon(Record) {
    return gicons["1"];
}
function makeMarker(i,isSelected) {
    var dt = Records[i].YR+"/"+
		     Records[i].MO+"/"+
			 Records[i].DY+":"+
		     Records[i].HR;
    var lat = parseFloat(Records[i].LAT);
    var lng = parseFloat(Records[i].LON);
    if(lat==null || lng==null ||
	   Records[i].LAT==null || Records[i].LON==null) { return; }
   // Only mark the first of a series of port locations
    if(i>0 && Records[i-1].LI==6 && Records[i].LI==6
       && Records[i-1].LAT==Records[i].LAT 
       && Records[i-1].LON==Records[i].LON) { 
        return;
    }
    var point = new GLatLng(lat,lng);
   // Create the marker
   if(isSelected) {
        var marker = new GMarker(point,
               {icon:gicons["0"],title:dt,zIndexProcess:bigZIndex});
   }
   else {
        var iconR = setIcon(Records[i]);
        var marker = new GMarker(point,{icon:iconR,title:dt});
   }
   // Clicking on the marker selects the associated record
   if(marker!=null) {
       GEvent.addListener(marker, "click",
           function() { 
  	         setSelected(i);
	         document.getElementById("record_p"+i).scrollIntoView();
           } );
   }
   return marker;
}

// Calculate a min zoom level to show the marker
function zoomLevel(i) {
	var ident = "";
	if(Records[i].ID != null) { ident += Records[i].ID; }
	if(Records[i].YR != null) { ident += Records[i].YR; }
	if(Records[i].MO != null) { ident += Records[i].MO; }
	var Location = [];
	Location[0] = parseInt(Records[i].LAT/5)+" "+parseInt(Records[i].LON/5);
	Location[1] = parseInt(Records[i].LAT/2)+" "+parseInt(Records[i].LON/2);
	Location[2] = parseInt(Records[i].LAT/1)+" "+parseInt(Records[i].LON/1);
	if(boxH[ident+Location[0]]==null) {
		boxH[ident+Location[0]]=1;
		boxH[ident+Location[1]]=1;
		boxH[ident+Location[2]]=1;
		return 0;
	}
	else if(boxH[ident+Location[1]]==null) {
		boxH[ident+Location[1]]=1;
		boxH[ident+Location[2]]=1;
		return 3;
	}
	else if(boxH[ident+Location[2]]==null) {
		boxH[ident+Location[2]]=1;
		return 5;
	}
	return 7;	
}


// Set one record as selected 
function setSelected(i) {

    if(lastSelected!=null) {
       // If reselection of same record - pop up an editor
		if(lastSelected==i) { 
			var w = open(
        "/philip/job/imma/online_editor/html/edit_record.html",
              "Edit Record "+i,
	          "width=630,height=550,status=yes,resizable=yes");
            return;
        }
       // Otherwise unset the previous selection:
       //   Reset colour of text and marker.
        document.getElementById("record_p"+
                            lastSelected).style.backgroundColor='white';
		try{  // Prevents odd error in Google code from stopping script
		    if(allmarkers[lastSelected]!=null) {
                allmarkers[lastSelected].setImage(setIcon(Records[lastSelected]).image);
		    }
		}
		catch (e) {}
    }
    
   // Select new record
   // Set text rep of record to grey background and move into view
    document.getElementById("record_p"+i).style.backgroundColor='lightgrey';
   // Pop up a yellow marker at selected location
   //  Delete old managed marker (may not be visible) and replace with
   //   an unmanaged (always visible) yellow marker 
    if(allmarkers[i]!=null) {
		mm.removeMarker(allmarkers[i]);
    }
	allmarkers[i] = makeMarker(i,true);
    if(allmarkers[i]!=null) {
    	map.addOverlay(allmarkers[i]);
    }
   // Remember the selection 
	lastSelected=i;
}
 
function updateRecord(rec,id) {
	Records[id]=rec;
  // Update the text in the record_div
	var pTmp = document.createTextNode(Records[id].string);
	document.getElementById("record_p"+id).firstChild.removeChild(
	            document.getElementById("record_p"+id).firstChild.firstChild);
	document.getElementById("record_p"+id).firstChild.appendChild(pTmp);
  // Update the marker position
             var lat = parseFloat(Records[id].LAT);
             var lng = parseFloat(Records[id].LON);
             if(lat==null || lng==null ||
			    Records[id].LAT==null || Records[id].LON==null) {
				try {
					map.removeOverlay(allmarkers[id]);
				}
				catch(e) {}
				try { 
					mm.removeMarker(allmarkers[id]);
					}
				catch(e) {}
		     }
			 else {
             	var point = new GLatLng(lat,lng);
			 	allmarkers[id].setPoint(point);
			}
}

// Output all the records in another window
function outputRecords() {
    var w = open();
	w.document.write("<html><head></head><body><pre>");
	for(var i=0;i<Records.length;i++) {
		w.document.writeln(Records[i].string);
	}
	w.document.write("</pre></body></html>");
	return;
}


}
// display a warning if the browser was not compatible
else {
 document.getElementById("map_div").innerHTML = "Sorry, the IMMA Editor won't work with your browser (it isn't compatible with the Google Maps API)";
}
  
