var app;
var layersPanel;
var areaPanel;
var findAreaPanel;
var setAreaPanel;
var notifyPanel;
var gpxPanel;
var downloadPanel;
var historyPanel;
var uploadPanel;
var servicesPanel;
var emailAddress="";
var mapPage;
var splashPage;
var currentAreaName="";
var mask=true;
var service="";

var APPBASE  = "/nafi2/";
var nafiUrl  = "http://"+document.location.host +"/nafi2/nafi";

globals.token="";

  function about(){
  window.open("about/about.htm","_BLANK");
  }

function addCustomArea(){
  var style="dialogWidth:400px;dialogHeight:300px;dialogLeft:" + this.screenX;
  var result=showModalDialog("control/addarea.htm",globals.token,style).split("%");
  if( result=="" || result==null)
    return;
  var extent=globals.theMap.mapExtent.join(",");
  var reply=getServerData("?command=addCustomArea&name=" + result[1] + "&notify=" + result[0] +"&extent=" + extent+ "&token=" + globals.token);
  if(reply.indexOf("Error:")==0)
    alert(reply) ;
  else
    loadCustomAreaTree();
}

  function addGroup(tv,group,extent){
  // if node already exists return group else create new one
  for (var n=0;n<tv.rootNode.children.childNodes.length;n++){
    if(tv.rootNode.children.childNodes[n].id==group)
      return tv.rootNode.children.childNodes[n].owner;
  }
  var newNd= new TreeNode(document,group,"","nodeClosed",extent);
  tv.addNode(tv.rootNode,newNd);
      return newNd;
  }

/*
function clearCustomArea(){
  globals.theMap.mode="update";
  globals.theMap.setAreaOfInterest('clear',null,null,null,null,false,null);
  globals.theMap.areaOfInterest.name="";
  document.getElementById("areaName").value="";
  refreshMap();
  setTimeout(bx,100);
  }
*/
function deleteCustomArea(){
  var style="dialogWidth:400px;dialogHeight:300px;dialogLeft:" + this.screenX;
    var result=showModalDialog("control/deletearea.htm",currentAreaName,style);
  if( result=="" || result==null)
    return;
  var reply=getServerData("?command=deleteCustomArea&name=" + result + "&token=" + globals.token);
  if(reply.indexOf("No rec")==0)
    alert(reply +" - if you are registered you need to log in before you can delete areas - if you have logged in your session may have expired - log in again.") ;
  else
    loadCustomAreaTree();
}

function deletePass(){
	var reply;
	var aoi="";
    var style="dialogWidth:400px;dialogHeight:250px;dialogLeft:" + top.screenX;
    result=showModalDialog("control/deletepass.htm"," ",style);
    if( result=="" || result==null)
        return;
    var parms=result.split(":");
    if(parms[1]=="true")
        aoi=globals.theMap.areaOfInterest.polygon;
	reply=getServerData("?command=deletePass&logid=" + parms[0] +
        "&token=" + globals.token + "&polygon=" + aoi);
  if(reply.indexOf("Error:")==-1){
      alert("Pass " + pass + " is deleted") ;
  }
  else
      alert(reply) ;
}

  function download(type){
  	if(type=="point")
  		window.open("control/downloadpointdata.htm?" + globals.theMap.mapExtent.join(","),"_BLANK");
  	else if(type=="raster"){
  	var ext=globals.theMap.mapExtent;
  	if(ext[2]-ext[0]>4 || ext[3]-ext[1]>4)
  	   alert("Area too large - maximum extent for this download is 4 degrees lon or lat");
  	 else 
  		window.open("control/downloadrasterdata.htm?" + globals.theMap.mapExtent.join(","),"_BLANK");
    }
	}

function editCustomAreas(){
  var style="dialogWidth:400px;dialogHeight:800px;dialogLeft:" + this.screenX;
  var result=showModalDialog("control/editarea.htm",userAreas,style);
  if( result=="" || result==null)
    return;
//	window.open("control/editarea.htm?" + userAreas,"EDITAREAS");
//  if(globals.token=="")
//    cmd="?command=updatecustomareas&token=null&data=" + result;
//  else
//    cmd="?command=updatecustomareas&token=" + globals.token + "&data=" + result;
  var reply=getServerData("?command=updatecustomareas&data=" + result + "&token=" + globals.token);
  if(reply.indexOf("No")==0 )
      alert("No Records updated. Note, you must be logged in to update areas that are attached to a login id");
  else
      alert(reply);
  loadCustomAreaTree();    
}

var t2;
var t3;
function initialiseSite(search){
  if(navigator.userAgent.indexOf("Mobile")!=-1){
	  alert("This site does not work on a mobile platform");
	  return;}
  if(search!=null && search!="")
    service=search.split("=")[1];
  app=new App("200",true,false,0);
  splashPage=new Page(false);
  splashPage.setContent("splash.htm");

  app.addPage(splashPage);

  mapPage=new Page(true);
  mapPage.setContent("control/map.htm");

  app.addPage(mapPage);
    drawControls();
  loadAreaTree();
  if(globals.theMap==null || globals.theMap=="undefined")
      t3=setTimeout(setupMap,500);
      t2=setTimeout(initLoad,1500);
  loadCustomAreaTree();
}

var t;
function initLoad()
{
  clearTimeout(t2);
  if(globals.theMap==null)
    t=setTimeout(initLoad,500);
  else{
    clearTimeout(t);
    loadLayerTree();
    loadBasemapList();
    app.showPage(splashPage);
    app.openPanel(areaPanel);
    app.toolbar.addToolbarButton("showsplash", showSplash,"Home page","images/icons/tool-home.gif");
    app.toolbar.addToolbarButton("showmap", showMap,"Show the map","images/icons/tool-map.gif");
    app.toolbar.addToolbarButton("showcloud",showCloud,"Get Cloud Image","images/icons/tool-cloud-image.gif");
    app.toolbar.addToolbarButton("viewpass", viewPass,"View satellite pass","images/icons/tool-satellite.gif");
    app.toolbar.addToolbarButton("extractmap", extractMap,"Extract map for device","images/icons/tool-download.gif");
    app.toolbar.addToolbarButton("fireline", fireLine,"GPX fire line","images/icons/tool-fire-line.gif");
    app.toolbar.addToolbarButton("viewlog", viewLog,"Latest satellite data","images/icons/tool-upload.gif");
    app.toolbar.addToolbarButton("login", login,"Log On","images/icons/tool-logon.gif");
    app.toolbar.addToolbarButton("logout", logout,"Log Off","images/icons/tool-logoff.gif");
    app.toolbar.addToolbarButton("spacer",spacer,"-");
    app.toolbar.addToolbarButton("spacer",spacer,"-");
//    app.toolbar2.addToolbarButton("standard", setMapType,"Std Map");
//    app.toolbar2.addToolbarButton("cloud", setMapType,"Cloud Map");
//    app.toolbar2.addToolbarButton("firehistory", setMapType,"Firescar Map");
  }
}

function setMapType(e){
/*    var p;
    if(ie){
        p=event.srcElement;
        }
   else
       p=e.target;
//   alert(p.id);
*/
   switch(e){
       case "standard":
		document.getElementById("LAST48_HOTSPOTS").childNodes[3].checked=true;
        document.getElementById("FSCURRENT_G").childNodes[3].checked=true;
		document.getElementById("FSMCURRENT_G").childNodes[3].checked=false;
		document.getElementById("AUTOFS").childNodes[3].checked=false;
        document.getElementById("FSM2010_G").childNodes[3].checked=false;
        document.getElementById("FSM2009_G").childNodes[3].checked=false;
		document.getElementById("FSM2008_G").childNodes[3].checked=false;
		document.getElementById("FSM2007_G").childNodes[3].checked=false;
		document.getElementById("FSM2006_G").childNodes[3].checked=false;
		document.getElementById("FS2010_G").childNodes[3].checked=false;
		document.getElementById("FS2009_G").childNodes[3].checked=false;
		document.getElementById("FS2008_G").childNodes[3].checked=false;
		document.getElementById("FS2007_G").childNodes[3].checked=false;
		document.getElementById("FS2006_G").childNodes[3].checked=false;
		document.getElementById("FS2005_G").childNodes[3].checked=false;
		document.getElementById("FS2004_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQ250M_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQL250M_G").childNodes[3].checked=false;
		document.getElementById("FIRETSLB250M_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQ1K_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQL1K_G").childNodes[3].checked=false;
		document.getElementById("FIRETSLB1K_G").childNodes[3].checked=false;
  			if(lastBg!=null){
          setBasemap(lastBg);
  				lastBg=null;
  			}
        break;
       case "firehistory":
		document.getElementById("LAST48_HOTSPOTS").childNodes[3].checked=true;
        document.getElementById("FSCURRENT_G").childNodes[3].checked=false;
		document.getElementById("FSMCURRENT_G").childNodes[3].checked=true;
		document.getElementById("AUTOFS").childNodes[3].checked=false;
        document.getElementById("FSM2010_G").childNodes[3].checked=true;
        document.getElementById("FSM2009_G").childNodes[3].checked=true;
		document.getElementById("FSM2008_G").childNodes[3].checked=false;
		document.getElementById("FSM2007_G").childNodes[3].checked=false;
		document.getElementById("FSM2006_G").childNodes[3].checked=false;
		document.getElementById("FS2010_G").childNodes[3].checked=false;
		document.getElementById("FS2009_G").childNodes[3].checked=false;
		document.getElementById("FS2008_G").childNodes[3].checked=false;
		document.getElementById("FS2007_G").childNodes[3].checked=false;
		document.getElementById("FS2006_G").childNodes[3].checked=false;
		document.getElementById("FS2005_G").childNodes[3].checked=false;
		document.getElementById("FS2004_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQ250M_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQL250M_G").childNodes[3].checked=false;
		document.getElementById("FIRETSLB250M_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQ1K_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQL1K_G").childNodes[3].checked=false;
		document.getElementById("FIRETSLB1K_G").childNodes[3].checked=false;
  			if(lastBg!=null){
          setBasemap(lastBg);
  				lastBg=null;
  			}
        break;
		    case "autoscars":
		document.getElementById("LAST48_HOTSPOTS").childNodes[3].checked=true;
        document.getElementById("FSCURRENT_G").childNodes[3].checked=true;
		document.getElementById("FSMCURRENT_G").childNodes[3].checked=false;
		document.getElementById("AUTOFS").childNodes[3].checked=true;
        document.getElementById("FSM2010_G").childNodes[3].checked=false;
        document.getElementById("FSM2009_G").childNodes[3].checked=false;
		document.getElementById("FSM2008_G").childNodes[3].checked=false;
		document.getElementById("FSM2007_G").childNodes[3].checked=false;
		document.getElementById("FSM2006_G").childNodes[3].checked=false;
		document.getElementById("FS2010_G").childNodes[3].checked=false;
		document.getElementById("FS2009_G").childNodes[3].checked=false;
		document.getElementById("FS2008_G").childNodes[3].checked=false;
		document.getElementById("FS2007_G").childNodes[3].checked=false;
		document.getElementById("FS2006_G").childNodes[3].checked=false;
		document.getElementById("FS2005_G").childNodes[3].checked=false;
		document.getElementById("FS2004_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQ250M_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQL250M_G").childNodes[3].checked=false;
		document.getElementById("FIRETSLB250M_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQ1K_G").childNodes[3].checked=false;
		document.getElementById("FIREFREQL1K_G").childNodes[3].checked=false;
		document.getElementById("FIRETSLB1K_G").childNodes[3].checked=false;
  			if(lastBg!=null){
          setBasemap(lastBg);
  				lastBg=null;
  			}
        break;
       case "cloud":
				lastBg=globals.theMap.currentBasemap;
    		setBasemap("BASEMAP");
        document.getElementById("MODIS_G").childNodes[3].checked=true;
        document.getElementById("FIRETSLB2Y_G").childNodes[3].checked=false;
        document.getElementById("FSCURRENT_G").childNodes[3].checked=false;
			}
       refreshMap();
    }
    
function drawControls(){
// resetAOI=false;

  areaPanel=new Panel("<img src=\"images/icons/side-region.gif\" class=\"left-icon\"> Fire Map Regions",true);
  areaPanel.panelHeader.className="panelheadermc_";
  areaPanel.setContentHtml(
  "<div align=\"center\">Map Type</div>" +
      "<div style=\"padding-bottom:5px;padding-top:5px\">" +
      "<button class=\"btn\" style=\"width:55px\" onclick=\"setMapType('standard')\">Std Map</button>" +
 //     "<button  class=\"btn\" style=\"width:45px\" onclick=\"setMapType('cloud')\">Cloud</button>" +
      "<button class=\"btn\" style=\"width:60px\" onclick=\"setMapType('firehistory')\">3yr scars</button>" +
	  "<button class=\"btn\" style=\"width:70px\" onclick=\"setMapType('autoscars')\">Auto scars</button></div>" +
  "<div id=\"areaTree\"></div><div id=\"customAreaTree\"></div>");
  app.addPanel(areaPanel);

  findAreaPanel=new Panel("<img src=\"images/icons/side-location.gif\" class=\"left-icon\"> " +
  "Go To Location",true);
  findAreaPanel.panelHeader.className="panelheadermc_";
  findAreaPanel.setContentUrl("control/findarea.htm",250,"none");
  app.addPanel(findAreaPanel);


  setAreaPanel=new Panel("<img src=\"images/icons/side-highlight.gif\" class=\"left-icon\"> Fire Reports",true);
  setAreaPanel.panelHeader.className="panelheadermc_";
  setAreaPanel.setContentUrl("control/report.htm",560,"none");
  setAreaPanel.addEvent("mouseClick",showMap);
  app.addPanel(setAreaPanel);


  layersPanel=new Panel("<img src=\"images/icons/side-layers.gif\" class=\"left-icon\"> Map Layers",true);
  layersPanel.panelHeader.className="panelheadermc_";
  layersPanel.setContentHtml("<div style=\"width:180px;\"><span style=\"font-size:9pt\">Features in layers marked * become visible as you zoom in</span><br><br>" +
  "<div style=\"font-size:8pt\">Background: <select style=\"font-size:8pt\" id=\"selectBM\" class=\"dropdownlist\" onChange=\"setBasemap(this.options[selectedIndex].value)\">" +
  "</select></div>" +
//  "<table><tr><td style=\"width:80\" class=\"llhead\">  </td><td style=\"width:50\" class=\"llhead\"></td>" +
//  "<td style=\"width:60\" class=\"llhead\">Active</td><td style=\"width:20\" class=\"llhead\">Visible</td></tr></table>" +
  "<br><div id=\"layerTree\"></div><div align=\"center\">" +
  "<button class=\"btn\" onClick=\"refreshMap()\">Refresh map</button><br>" +
  "<button class=\"btn\" onClick=\"setDefaults()\">Set as default</button> </div>");
  app.addPanel(layersPanel); 

historyPanel=new Panel("<img src=\"images/icons/side-history.gif\" class=\"left-icon\"> History",false);
  historyPanel.panelHeader.className="panelheadermc_";
  historyPanel.setContentHtml("<div>Mapview history - Oldest first</div><table id=\"historyTable\" class=\"panelItemTable\" cellpadding=\"0\" cellspacing=\"5\" ></table>");
  app.addPanel(historyPanel);

notifyPanel=new Panel("<img src=\"images/icons/side-email.gif\" class=\"left-icon\"> Fire Email Alerts",false);
  notifyPanel.panelHeader.className="panelheadermc_";
  notifyPanel.setContentUrl("about/hsnotifications.htm",300,"none");
  app.addPanel(notifyPanel);
  
downloadPanel=new Panel("<img src=\"images/icons/side-download.gif\" class=\"left-icon\"> Download Data",true);
  downloadPanel.panelHeader.className="panelheadermc_";
  downloadPanel.setContentHtml("<div  style=\"text-align:center;font-size:9pt;font-family:Tahoma;width:90%\">" +
	"Download full data sets for <b>all of Northern Australia</b><br>" +
      "<button class=\"btn\" onclick=\"window.open('about/ausfrqdownload.htm','_BLANK')\">Fire history data</button><br>" +
      "<button class=\"btn\" onclick=\"window.open('about/firescarmaps.htm','_BLANK')\">Fire scar data</button><br>" +
"Download Hotspot and Lightning Data for <b>Displayed Map Area</b><br>" +
      "<button class=\"btn\" onclick=\"download('point')\">Hotspots</button><br>" +
      "<button class=\"btn\" onclick=\"download('raster')\">Firescars</button><br>" );
  app.addPanel(downloadPanel);
  
uploadPanel=new Panel("<img src=\"images/icons/side-upload.gif\" class=\"left-icon\"> Upload Data",true);
  uploadPanel.panelHeader.className="panelheadermc_";
  uploadPanel.setContentHtml("<div  style=\"text-align:center;font-size:9pt;font-family:Tahoma;width:90%\">" +
      "<button class=\"btn\" onclick=\"upload('ft')\">Fire Lines</button><br>" +
      "<button class=\"btn\" onclick=\"upload('fs')\">Fire Scars</button>");
  app.addPanel(uploadPanel);

servicesPanel=new Panel("<img src=\"images/icons/side-viewers.gif\" class=\"left-icon\"> Google Earth, WMS",true);
  servicesPanel.panelHeader.className="panelheadermc_";
  servicesPanel.setContentHtml("<div  style=\"text-align:center;font-size:9pt;font-family:Tahoma;width:90%\">" +
      "<button class=\"btn\" onclick=\"window.open('about/googleearth.htm','_BLANK')\">Google Earth</button><br>"+
      "<button class=\"btn\" onclick=\"window.open('about/wms.htm')\">WMS</button><br>");
  app.addPanel(servicesPanel);

aboutPanel=new Panel("<img src=\"images/icons/side-help.gif\" class=\"left-icon\"> Help & Useful Links",false);
  aboutPanel.panelHeader.className="panelheadermc_";
  aboutPanel.setContentHtml("<div  style=\"text-align:center;font-size:9pt;font-family:Tahoma;width:90%\">" +
      "<button class=\"btn\" onclick=\"window.open('about/about.htm','_BLANK')\">About NAFI</button><br>"+
      "<button class=\"btn\" onclick=\"window.open('about/links.htm','_BLANK')\">Useful Links</button><br>"+
      "<button class=\"btn\" onclick=\"window.open('help/help.htm','help' ,'height=500,width=500,left=400,top=400')\">Help</button><br>");
  app.addPanel(aboutPanel);



/*
linksPanel=new Panel("Links");
  linksPanel.panelHeader.className="panelheadermc_";
  linksPanel.setContentUrl("control/links.htm",200,"toolPanelId");
  app.addPanel(linksPanel);
*/
}

function extractMap(){  // zipped geotiff
    var reqMap=null;
	  var result;
	  var request;
	  if(print==false){
      var style="dialogWidth:400px;dialogHeight:200px;dialogLeft:" + top.screenX;
      result=showModalDialog("control/extractmap.htm"," ",style);
      if( result=="" || result==null)
        return;
    }
    if (typeof XMLHttpRequest!="undefined")
      reqMap= new XMLHttpRequest();
    else
      reqMap=new ActiveXObject("MSXML2.XMLHttp.3.0");
    app.showPage(mapPage);
  		//"?maprequest=" + "<?xml version=\"1.0\" standalone=\"yes\"?>" +
		if (print==true){
    request="<root><extent>" + globals.theMap.mapExtent.join(",") + "</extent>"  + globals.theMap.getLastRequest() + "</root>";
			reqMap.open("post","http://"+document.location.host +"/nafi2/printmap",false);
			print=false;
		}
    else{
      request="<root><extent>" + globals.theMap.mapExtent.join(",") + "</extent><mapname>" + result + "</mapname>" + globals.theMap.getLastRequest() + "</root>";
  		reqMap.open("post","http://"+document.location.host +"/nafi2/extractmap",false);
    }
    reqMap.send(request);
    window.open(reqMap.responseText,"_BLANK");
  }
  
var fireLineWin=null;
var flCount=0;
function fireLine(){  
//      var style="dialogWidth:400px;dialogHeight:200px;dialogLeft:" + top.screenX;
 //     result=showModelessDialog("control/fireline.htm",globals.theMap,style);
 flCount=0;
 fireLineWin=window.open("control/fireline.htm","_BLANK","height=200,width=400");
fireLineWin.focus();
 setTimeout(fireLine2,200);
  }
  
function fireLine2(){  
//  alert(fireLineWin);
//  alert(fireLineWin.map);
  if (fireLineWin==null || fireLineWin.map==null){
    if(flCount>2)
      return;
    setTimeout(fireLine2,1000);
    flCount++;
    return;
  }
  fireLineWin.map=globals.theMap;
  fireLineWin.document.getElementById("start").disabled=false;
}
function getCustomLayers(token){
    var count=0;
    var atts;
    var newLayer;
    var layerList=getServerData("?command=customLayerList&token=" + token );
    var layers=layerList.split("$$");
    if(layers.length==1) return;
    for(count=0;count<layers.length-1;count++){
        newLayer=new Layer();
        atts=layers[count].split("__");
        newLayer.layerType=atts[14];
        newLayer.layerGroup=atts[0];
        newLayer.layerName=atts[1];
        newLayer.title=atts[2];
        newLayer.dataSource=atts[3];
        newLayer.geometryType=atts[4];
        newLayer.geometryCol=atts[5];
        newLayer.infoQuery=atts[6];
        newLayer.jdbcQuery=atts[7];
        newLayer.infoColumnFormat=atts[8];
        newLayer.isEnabled=atts[15];
        newLayer.canBeActive=atts[9];
        newLayer.jdbcSymbol=atts[10];
        newLayer.jdbcLabel=atts[11];
        newLayer.minZoom=atts[12];
        newLayer.maxZoom=atts[13];
        globals.theMap.addLayer(newLayer);
    }
    loadLayerTree();
}

 function getServerData(cmd){
 var reqSD=null;
    if (typeof XMLHttpRequest!="undefined")
      reqSD= new XMLHttpRequest();
    else
      reqSD=new ActiveXObject("MSXML2.XMLHttp.3.0");
    reqSD.open("get",nafiUrl+cmd,false);
    reqSD.send(null);
    return(reqSD.responseText);
}


  function loadAreaTree(){
    var tb=document.getElementById("areaTree");
    var tv=new TreeView(document," Preset Areas","",regionClick,"arearoot");
    var rootNode=tv.rootNode;
    var areas=getServerData("?command=areaList").split(";"); // call nafisupport servlet
    while (tb.hasChildNodes() ) {
      tb.removeChild(tb.firstChild);
    }
    var nd;
    var ndG;
    var extent;

    var area;
    var group="arearoot";

   for (var i=0;i<areas.length-1;i++){
      area=areas[i].split(":");
      if(area[0]!=null && area[0]!=group){
        group=area[0];
        if (area[0]=="Cape York Pen'sla")
          extent="141.19,-16.70,145.65,-9.96";
        else if (area[0]=="North East Qld")
          extent="144.33,-20.02,148.81,-16.55";
        else if (area[0]=="The Gulf Qld")
          extent="137.99,-20.02,144.55,-16.56";
        else if (area[0]=="Central Qld")
          extent="146.45,-24.87,153.10,-19.84";
        else if (area[0]=="Central West Qld")
          extent="142.17,-24.87,146.69,-19.85";
        else if (area[0]=="Western Qld")
          extent="137.99,-24.87,142.39,-19.85";
        else if (area[0]=="South Qld")
          extent="141,-24.75,153,-29.4";
        else if (area[0]=="NT North")
          extent="129,-16.5,138,-11";
		  else if (area[0]=="NT Central")
          extent="129,-19,138,-14";
        else if (area[0]=="NT South")
          extent="130.5,-25.5,137.33,-21";
        else if (area[0]=="NW Australia")
          extent="121.66,-19,130,-13.5";
		else if (area[0]=="South Aust")
          extent="128.5,-34.75,143,-25.5";	
        ndG=addGroup(tv,group,extent);
      }
      else if (group=="arearoot")
        ndG=rootNode;
      nd=new TreeNode(document, area[1],"","leaf",area[2]);
      tv.addNode(ndG,nd);
  }
    tb.appendChild(rootNode.node);

  }

  var baseMaps;
  function loadBasemapList(){
    basemaps=globals.theMap.getBasemapList();
    setTimeout(loadBasemapList2,500);
  }

  function loadBasemapList2(){
    var bl=document.getElementById("selectBM");
    var opt;
    var bm;
    for (var i=0;i<basemaps.length;i++){
      bm=basemaps[i].split(",");
        opt=new Option(bm[1],bm[0],false,false);
      if(globals.theMap.ie)
        bl.add(opt);
      else
        bl.add(opt,null);
      if(bm[0]==globals.theMap.currentBasemap)
        bl.selectedIndex=i;
    }
		bm.selectedIndex=-1;
  }

    var userAreas="";

   function loadCustomAreaTree(){
    userAreas="";
    var uq=Math.random();
    var tb=document.getElementById("customAreaTree");
    var tv=new TreeView(document,"My Areas","",regionClick,"customarearoot");
    var rootNode=tv.rootNode;
    ua=getServerData("?command=customAreaList&uq=" + uq).split(";"); // call nafisupport servlet
    while (tb.hasChildNodes() ) {
      tb.removeChild(tb.firstChild);
    }
    var nd;
    var ndG;

    var area;
    var group="customarearoot";

   for (var i=0;i<ua.length;i++){
      area=ua[i].split(":");
      if(i<ua.length-3)
        userAreas+=area[1]+":"+area[3]+";";
      if(area[0]!=null && area[0]!=group){
        group=area[0];
        ndG=addGroup(tv,group);
      }
      else if (group=="customarearoot")
        ndG=rootNode;
      nd=new TreeNode(document,area[1],"","leaf",area[2]);
      tv.addNode(ndG,nd);
  }
    tb.appendChild(rootNode.node);

  }

  function loadHistoryTable(){
    var tb=document.getElementById("historyTable");
    var tr;
    var td;
    var x=globals.theMap.getHistory();
    var items=x.split(";");
    while (tb.rows.length>0) {
      tb.deleteRow(0);
    }
    for (var i=0;i<items.length-1;i++){
      tr=tb.insertRow(-1);
      td=tr.insertCell(-1);
      td.innerHTML=items[i];
      if(globals.theMap.ie)
          tr.attachEvent("onclick",showHistory);
      else
          tr.addEventListener("click",showHistory,false);
    }
  }

  function showHistory(e){
  var p;
    if(ie){
        p=event.srcElement.parentNode;
        }
   else
       p=e.target.parentNode;
    globals.theMap.setHistory(p.rowIndex);
  }

  function loadLayerTree(){
    var tb=document.getElementById("layerTree");
    var tv=new TreeView(document,"<table><tr><td style=\"width:100px;color:white;font-size:9pt\">Layers</td>" +
		"<td style=\"width:20px;font-size:8pt;color:white\">Inf</td><td style=\"width:20px;font-size:8pt;color:white\">Show</td></tr></table>","",nodeClick,"layerroot");
    var rootNode=tv.rootNode;
    var x=globals.theMap.getLayerList();
    var layers=x.split(";");
    while (tb.hasChildNodes() ) {
      tb.removeChild(tb.firstChild);
    }
    var nd;
    var ndG;
    var activateBtn;
    var showBtn;

    var lyr;
    var group="layerroot";

   for (var i=0;i<layers.length-1;i++){
      lyr=layers[i].split(",");
      if(lyr[0]!=null && lyr[0]!=group){
        group=lyr[0];
        ndG=addGroup(tv,group);
      }
      else if (group=="layerroot")
        ndG=rootNode;
      nd=new TreeNode(document,"<u>" + lyr[2] + "</u>"," ","leaf",lyr[1]);
        if(ie)
        activateBtn=document.createElement("<input type=\"radio\" name=\"activate\">");
      else{
        activateBtn=document.createElement("input");
        activateBtn.type="radio";
      }
      activateBtn.style.padding="0";
      activateBtn.style.margin="0";
      activateBtn.style.marginRight="5";
      activateBtn.style.marginLeft="5";
      activateBtn.name="activate";
      if(lyr[4]=="true"){
        activateBtn.checked=true;
        if(ie)
          activateBtn.defaultChecked=true;
      }
      if(lyr[5]=="false")
        activateBtn.disabled=true;
      nd.node.insertBefore(activateBtn,nd.node.lastChild);
      showBtn=document.createElement("input");
/*      if(lyr[0].indexOf("Fire H")>-1 || lyr[1]=="FSCURRENT_G"){
        if(ie)
           showBtn=document.createElement("<input type=\"radio\" name=\"firehist\">");
        else{
            showBtn.type="radio";
            showBtn.name="firehist";
        }
      }

      else
*/
      showBtn.type="checkbox";
      showBtn.style.padding="0";
      showBtn.style.margin="0";
      showBtn.style.marginRight="4";
      showBtn.style.marginLeft="0";
      if(lyr[3]=="true"){
        showBtn.checked=true;
        if(ie)
          showBtn.defaultChecked=true;
    }
      nd.node.insertBefore(showBtn,nd.node.lastChild);
      tv.addNode(ndG,nd);
  }
    tb.appendChild(rootNode.node);

  }

function login(){
	var parms;
	var reply;
	var result;
  var style="dialogWidth:400px;dialogHeight:300px;dialogLeft:" + top.screenX;
    result=showModalDialog("control/login.htm"," ",style);
  if( result=="" || result==null)
    return;
  else if( result=="Edit"){
    result=showModalDialog("control/editlogin.htm"," ",style);
		if( result=="" || result==null)
			return;
		else
			parms=result.split("%");
			reply=getServerData("?command=editlogin&oldemail=" + parms[0] + "&oldpwd=" + parms[1] +
				"&newemail=" + parms[2] + "&newpwd=" + parms[3]);
	}
	else{
		parms=result.split("%");
		if(parms.length>2)
		  reply=getServerData("?command=login&email=" + parms[0] + "&pwd=" + parms[1] + "&new=true");
		else
		  reply=getServerData("?command=login&email=" + parms[0] + "&pwd=" + parms[1]);
	}
  if(reply.indexOf("Error:")==-1){
    globals.token=reply;
    loadCustomAreaTree();
    getCustomLayers(reply);
    app.toolbar.msg.style.color="#00ff00";
 //     alert("You are now logged on") ;
      app.toolbar.msg.innerHTML="Logon successful - valid for 15 minutes";
      var tt1=setTimeout(clearMessage,5000);
  }
  else
      alert(reply) ;
}


function logout(){
    var reply=getServerData("?command=logout");
    app.toolbar.msg.style.color="#ffffff";
    app.toolbar.msg.innerHTML="Logged off";
    var tt1=setTimeout(clearMessage,5000);
}

    function clearMessage(){
        app.toolbar.msg.innerHTML="";
  }
  
var lastBg=null;

function nodeClick(pn){
  if(pn.type=="radio"){
    globals.theMap.setActiveLayer(pn.parentNode.id);
    pn.checked=true;
  }
  else if(pn.innerHTML.indexOf("<u>")==0)
    window.open("about/metadata.htm#_" +pn.parentNode.id,"nafimetadata");
  else if(pn.type=="checkbox" ){
    var groupList=document.getElementById("layerroot").childNodes[2].childNodes;
    var layerList;
    for (var p=0;p<groupList.length;p++){
      layerList=groupList[p].childNodes[2].childNodes;
      for (var q=0;q<layerList.length;q++){
        if(layerList[q].childNodes[3].checked)
          globals.theMap.setEnabled(layerList[q].id,true);
        else
          globals.theMap.setEnabled(layerList[q].id,false);
      }
    }
    }
    
    
 
	if( pn.parentNode.id.indexOf("_G")>0){
    var grp=pn.parentNode.parentNode.parentNode.childNodes[1].innerHTML;
		var groupList=document.getElementById("layerroot").childNodes[2].childNodes;
		var layerList;
		for (var p=0;p<groupList.length;p++){
		  if(groupList[p].childNodes[1].innerHTML==grp)
		    continue;
      layerList=groupList[p].childNodes[2].childNodes;
  		for (var q=0;q<layerList.length;q++){
    		if(layerList[q].id.indexOf("_G")>0){
      		layerList[q].childNodes[3].checked=false;
    		}
  		}
		}
  }
    		
 		if( pn.parentNode.id=="MODIS_G"){
			if(pn.checked==true){
				lastBg=globals.theMap.currentBasemap;
    				setBasemap("BASEMAP");
			}
			else if(lastBg!=null){
    				setBasemap(lastBg);
				lastBg=null;
			}
notifyMe();
		}
    var isChecked=pn.parentNode.childNodes[3].checked;
		if(pn.parentNode.id.indexOf("TSLB2Y")>-1){
		    document.getElementById("TSLB2YRW").childNodes[3].checked=isChecked;
          globals.theMap.setEnabled("TSLB2YRW",isChecked);
		    document.getElementById("TSLB2YR").childNodes[3].checked=isChecked;
          globals.theMap.setEnabled("TSLB2YR",isChecked);
}		
}


	function notifyMe(){
	   loadHistoryTable();
		return;
	  var bl=document.getElementById("selectBM");
		var i;
    for (i=0;i<bl.options.length;i++){
      if(bl.options[i].value==globals.theMap.currentBasemap){
        bl.selectedIndex=i;
				break;
			}
		}
	}

	var print=false;
	function printMap(){
	  print=true;
	  extractMap();
	}
  
  function regionClick(pn){
    app.showPage(mapPage);
  globals.theMap.setAreaOfInterest('none',null,null,null,null,false,null);
      if(pn.innerHTML.indexOf("add...")==0)
          addCustomArea();
      else if(pn.innerHTML.indexOf("delete...")==0)
          deleteCustomArea();
        else if(pn.innerHTML.indexOf("edit...")==0)
          editCustomAreas();
      else if(pn.parentNode.id.indexOf("1")==0){
          globals.theMap.zoomToCoords(pn.parentNode.id,globals.theMap.mode);
          currentAreaName=pn.innerHTML;
      }
  }
  
  function goToArea(area,name){
    globals.theMap.zoomToCoords(area,"zoomin");
    currentAreaName=name;
    app.showPage(mapPage);
  }
 

function refreshMap(){
var curMode=globals.theMap.mode;
  var groupList=document.getElementById("layerroot").childNodes[2].childNodes;
  var layerList;
  for (var p=0;p<groupList.length;p++){
    layerList=groupList[p].childNodes[2].childNodes;
    for (var q=0;q<layerList.length;q++){
      if(layerList[q].childNodes[3].checked)
        globals.theMap.setEnabled(layerList[q].id,true);
      else
        globals.theMap.setEnabled(layerList[q].id,false);
    }
  }
  globals.theMap.mode="update";
  globals.theMap.refresh(curMode);
}

var tResize;
function resizeMap(){
if(globals.theMap=="undefined" ||globals.theMap==null)
    return;
  globals.theMap.mapImg.src="blank.htm";
  if(globals.theMap!=null){
    clearTimeout(tResize);
    tResize=setTimeout(bz,1000);
  }
}

function bz(){

  splashPage.page.style.height=new Number(app.getHeight())-53;
  splashPage.page.style.width=app.getWidth()+10; //+15;
  splashPage.setContent("splash.htm");
  mapPage.page.style.height=new Number(app.getHeight())-55;
  mapPage.page.style.width=app.getWidth()+8;
   var mapWidth=globals.theMap.resize();
    app.toolbar.pallette.style.width=mapWidth+5;
}
/*
  function setArea(rowid,name){
    globals.theMap.areaOfInterest.name=name;
    globals.theMap.areaOfInterest.mask=mask;
    if(rowid=="RESET"){
      clearCustomArea();
    }
    else if(rowid=="polygon"){
      globals.theMap.setAreaOfInterest("draw",null,null,null,null,null,false,null);
    }
    else if(rowid=="current"){
      globals.theMap.setAreaOfInterest("rectangle",null,null,null,null,null,false,null);
    }
    else if(rowid=="all_nt"){
      globals.theMap.setAreaOfInterest("db",null,"nreta","special","AllNT",null,true,null);
      globals.theMap.mode="update";
      globals.theMap.refresh();
    }
    else{
      var table=document.getElementById("areaList").name;
      globals.theMap.setAreaOfInterest("db",null,"nafi",table,rowid,"GEOMETRY",true,aoiIdCol);
      globals.theMap.mode="update";
      globals.theMap.refresh();
    }
    setTimeout(bx,100);
  }

*/



var aoiIdCol;
  function setBasemap(bm){
  if(bm=="-")
    return;
    if(bm=="BASEMAPM"){
      // turn on modis layer
      document.getElementById("MODIS_G").childNodes[3].checked=true;
      globals.theMap.setEnabled("MODIS_G",true);
    }
    globals.theMap.setBasemap(bm);
  }

  function setCustomArea(type,btn){
    globals.theMap.clearClientLayers();
    if(type=="click"){
      btn.style.backgroundColor="red";
      globals.theMap.setAreaOfInterest("db","false","nafi","property","click","geometry",false,null);
  }
  else
      globals.theMap.setAreaOfInterest("polygon","Custom",null,"null",null,false,null);
    setTimeout(bx,100);
  }

  function setDefaults(){
    var groupList=document.getElementById("layerroot").childNodes[2].childNodes;
    var layerList;
    var enabledLayers="";
    for (var p=0;p<groupList.length;p++){
      layerList=groupList[p].childNodes[2].childNodes;
        for (var q=0;q<layerList.length;q++){
          if(layerList[q].childNodes[3].checked)
            enabledLayers +="$" + layerList[q].id + "$";
        }
    }
    var activeLayer=globals.theMap.getActiveLayer();
    var basemap=globals.theMap.currentBasemap;
    var showLegend=globals.theMap.showLegend;
    var showRefmap=globals.theMap.showRefmap;
    var result=getServerData("?command=setDefaults&showlegend=" + showLegend + "&showrefmap=" + showRefmap +
      "&basemap=" +basemap +"&activelayer=" +activeLayer +"&enabledlayers=" + enabledLayers);
    if(result.indexOf("Error")==0)
      alert(req.responseText) ;
    else{
      alert("Current map settings have been set as default. (Including current settings for Reference Map and Legend visibility") ;
    }
  }

  function setLayerActive(btn){
   var lyrName=btn.parentNode.parentNode.childNodes[3].getAttribute("abbr");
    globals.theMap.setActiveLayer(lyrName);
  }

  function setMask(bool){
    mask=bool;
    }
    /*
  function setOption(type){
        document.getElementById("pickArea").style.display="none";
    var query;
    switch(type){
      case "RESET":
          clearCustomArea();
        return;
      case "BIOREGIONS":
        query="select name,id from bioregions order by name";
        aoiIdCol="id"
        setTimeout(bx,100);
        break;
      case "PARKS_TABLE":
        query="select name,rowidtochar(rowid) from parks_table order by name";
        aoiIdCol="rowid"
        setTimeout(bx,100);
        break;
      case "T_LOCALGOV":
        query="select name,id from t_localgov order by name";
        aoiIdCol="id"
        setTimeout(bx,100);
        break;
    }
    document.getElementById("pickArea").style.display="block";
    var list=document.getElementById("areaList");
    list.name=type;
    if (list.hasChildNodes()){
       while(list.childNodes.length>0)
         list.removeChild(list.firstChild);
    }
    var areas=getServerData("?command=areaList").split(";"); // call nafisupport servlet
    
    var QResult=globals.theMap.getData("nafi",query,null,null,"nonspatial");
    if(QResult!=null){
      var result=QResult.split("^");
    var item;
    var opt;
      opt=new Option("Select","RESET",false,false);
      if(navigator.appName=="Netscape")
        list.add(opt,null);
      else
        list.add(opt);
    for (var i=1;i<result.length-1;i++){
      item=result[i].split(",");
      opt=new Option(item[0],item[1],false,false);
      if(navigator.appName=="Netscape")
        list.add(opt,null);
      else
        list.add(opt);
    }
    }
  }

  function bx(){
    app.openPanel(setAreaPanel,false);
    setTimeout(by,100);
  }

  function by(){
    app.openPanel(setAreaPanel,true);
  }
*/

function setupMap(){
         var t4=setTimeout(setupMap2,2000);
}
function setupMap2(){
    clearTimeout(t3)
    if(mapPage.win==null || mapPage.win=="undefined"){
           t3=setTimeout(setupMap2,500);
          }
    else{
      var STARTEXT = "129,-26,138,-10.5";
      var BASEURL  = "http://"+document.location.host + APPBASE;
      var HASREFMAP=false;
      var USECOOKIE=true;
      var SHOWLEGEND=true;
         globals.theMap=new Map(BASEURL,mapPage.win,STARTEXT,HASREFMAP,USECOOKIE,0,0,"LAST48_HOTSPOTS",SHOWLEGEND,service);
      globals.theMap.setNotify(notifyMe);
      globals.theMap.setPrint(printMap);
      globals.theMap.areaOfInterest.mask=true;
    }
  }

function showCloud(){
  var height=new Number(app.getHeight()-40);
//  var width=new Number(app.getWidth());
  if(globals.theMap!=null && globals.theMap!="undefined" ){
var s="http://sentinel.ga.gov.au/wmsconnector/com.esri.wms.Esrimap?REQUEST=GetMap&VERSION=1.1.1&FORMAT=image/png&ServiceName=GDA94_Sentinel_Shapefiles_WMS&" + "LAYERS=1802&STYLES=&TRANSPARENT=TRUE&EXCEPTIONS=application/vnd.ogc.se_xml&SRS=EPSG:4326&HEIGHT=" + height + "&WIDTH=" + app.getWidth() + "&BBOX=";
// alert(width + " - " +height);
  		window.open(s +  globals.theMap.mapExtent.join(","),"_BLANK");
  		}
}

  function showMap(){
    app.showPage(mapPage);
  }

  function showSplash(){
    app.showPage(splashPage);
  }

  function spacer(){
  return;
  }

  function viewLog(){
      window.open("control/viewlog.htm","_BLANK");
      }



passShown=false;
function viewPass(){
	if(passShown==true){
		globals.theMap.removeLayerByName("satpass");
		passShown=false;
	}
		var style="dialogWidth:500px;dialogHeight:250px;dialogLeft:" + top.screenX;
			var logId=showModalDialog("control/viewpass.htm"," ",style);
		if( logId=="" || logId==null){
			refreshMap();
			return;
			}
		if(logId=="delete")
		  deletePass();
		else{
			var extent=getServerData("?command=hsMBR&logid=" + logId);
			if(extent.indexOf("Error:")==-1 && extent!=""){
				globals.theMap.mapExtent=extent.split(",");
				globals.theMap.mapExtent[0]-=1.0;
				globals.theMap.mapExtent[1]-=1.0;;
    				globals.theMap.mapExtent[2]-=-1.0;
    				globals.theMap.mapExtent[3]-=-1.0;
				var layerName="satpass";
				globals.theMap.removeLayerByName(layerName);
				var newLayer=new Layer();
				newLayer.layerType="jdbc";
				newLayer.layerGroup="Hotspots";
				newLayer.layerName="satpass";
				newLayer.title="Satellite Pass " +logId;
				newLayer.dataSource="nafi";
				newLayer.geometryType="point";
				newLayer.geometryCol="GEOM";
				newLayer.infoQuery="none";
				newLayer.detailQuery="none";
				newLayer.jdbcQuery="select geom from hotspots where logid= " + logId
				newLayer.infoColumnFormat="";
				newLayer.detailColumnFormat="";
				newLayer.isEnabled=true;
				newLayer.dontDisplay=false;
				newLayer.canBeActive=false;
				newLayer.jdbcUrl="datasource";
				newLayer.jdbcSymbol="M.MARKPASS";
				newLayer.jdbcLabel="null";
				newLayer.minZoom="100";
				newLayer.maxZoom="0";
				globals.theMap.addLayer(newLayer);
				loadLayerTree();
				passShown=true;
			refreshMap();
			}
else
	alert("Pass not found");
    }
    app.showPage(mapPage);
		}
		
function upload(type){
	if(globals.token=="")
		alert("You must be logged in to use this tool");
	else
	{
	if(type=="fs")
		window.open("control/fsupload.htm?" + globals.token,"_BLANK");
	else if(type=="ft")
		window.open("control/ftupload.htm?" + globals.token,"_BLANK");
	}
}


