var mapservURL = '/bin/mapserv46';
var goTo = 'zoomin';
var alreadyOpen = false;
var popupWin;
var winID;
// **************************************************************************************************
function openWindow(url,newPage) {
  if (alreadyOpen) {
    if (!popupWin.closed) popupWin.close(); }
  else alreadyOpen = true;
  popupWin = window.open(url,newPage,'scrollbars,menubar,resizable,top=0,left=50,screenX=50,screenY=0,width='+parseInt(screen.width*0.85)+',height='+parseInt(screen.height*0.85));
}
// **************************************************************************************************
function ChangeClassById(ContainerId,NodeId){
  var InactiveClass = "btn";
  var ActiveClass = "btn_active";
  var TagName = "a";
  var Container = document.getElementById(ContainerId);
  var Nodes = Container.getElementsByTagName(TagName);
  for (CurrentNode=0; CurrentNode<Nodes.length; CurrentNode++) {
   if(Nodes[CurrentNode].getAttribute("id") == NodeId) {
    Nodes[CurrentNode].className = ActiveClass; }
   else {
    Nodes[CurrentNode].className = InactiveClass; }
  }
}
// **************************************************************************************************
function setGoTo(curButt,chgGoTo) {
  goTo = chgGoTo;
  ChangeClassById('butts', curButt);
  if (goTo == 'oz' || goTo == 'legend' || goTo == 'print') changeMap();
}
// **************************************************************************************************
function getBox() {
  mF = document.mapframeform;
  curExt = mF.mapext.value;
  mapImg = mF.mapimg;

  ext = curExt.split(' ');
  rb = mF.xy.value.split(' ');
  minLong = parseFloat(ext[0]);
  minLat = parseFloat(ext[3]);
  longExt = parseFloat(ext[2]) - minLong;
  latExt = minLat - parseFloat(ext[1]);
  x1 = Math.round((minLong + (parseInt(rb[0])/mapImg.width)*longExt)*10000)/10000;
  x2 = Math.round((minLong + (parseInt(rb[2])/mapImg.width)*longExt)*10000)/10000;
  y1 = Math.round((minLat - (parseInt(rb[3])/mapImg.height)*latExt)*10000)/10000;
  y2 = Math.round((minLat - (parseInt(rb[1])/mapImg.height)*latExt)*10000)/10000;

  // Handle point (not box) input ie create a box around the point (approx 1km)
  if (x1 == x2 && y1 == y2) {
    // for smartlines interested in pretty much a point so create a much smaller box
   if (window.top.document.getElementById("gPageName").value == 'smartline') {
      x1 = x1 - 0.0001;
      x2 = x2 + 0.0001;
      y1 = y1 - 0.0001;
      y2 = y2 + 0.0001; 
    }
    else {
      x1 = x1 - 0.005;
      x2 = x2 + 0.005;
      y1 = y1 - 0.005;
      y2 = y2 + 0.005; 
    }
  }
  curExt = x1+' '+y1+' '+x2+' '+y2;
  return curExt;
}
// **************************************************************************************************
function setSelect() {
  mf = window.top.document.mapform;
  mf.pState.selectedIndex = 0;
//  mf.pCMA.selectedIndex = 0;
  mf.pImcra.selectedIndex = 0;
  mf.pMarReg.selectedIndex = 0;
  mf.pNRMZone.selectedIndex = 0;
}
// **************************************************************************************************
function getExtent (curExt, rb, action) {
// for functionality like panning and zooming out map servers calculates its own extent. 
// need to duplicate it here as we need to know the new extent to update summary data

  var ext = curExt.split(' ');
  var xx = ((ext[2] - ext[0])/440)*(((parseInt(rb[0])+parseInt(rb[2]))/2)-220);
  var yy = ((ext[3] - ext[1])/360)*(((parseInt(rb[1])+parseInt(rb[3]))/2)-180);
  var ex0 = Math.round((parseFloat(ext[0])+xx)*1000000)/1000000;
  var ex1 = Math.round((parseFloat(ext[1])-yy)*1000000)/1000000;
  var ex2 = Math.round((parseFloat(ext[2])+xx)*1000000)/1000000;
  var ex3 = Math.round((parseFloat(ext[3])-yy)*1000000)/1000000;

  if (action == "zoomout") {
    ex0 = ex0 - (ext[2] - ext[0])/2;
    ex1 = ex1 - (ext[3] - ext[1])/2;
    ex2 = ex2 + (ext[2] - ext[0])/2;
    ex3 = ex3 + (ext[3] - ext[1])/2;
  }
  
  return ex0 + ' ' + ex1 + ' ' + ex2 + ' ' + ex3;
}
// **************************************************************************************************
function changeMap() {
	
  pageName = window.top.document.getElementById("gPageName").value;
	
  mf = window.top.document.mapform;
  mF = document.mapframeform;
  mFsrc = window.top.frames['mapframe'].location;
  mapFile = mF.map.value;
  mapfileExt = mF.mapfile_ext.value;
  curExt = mF.mapext.value;
  mapExt = mF.mapext.value;
  mapImg = mF.mapimg;

  mapFilter = '&mapfiltername=' + mF.mapfiltername.value + '&mapfiltername2=' + mF.mapfiltername2.value + '&mapfilter=' + mF.mapfilter.value;
	
  frameSrc = mapservURL + '?map=' + mapFile + '&mapfile_ext=' + mapfileExt + mapFilter;
  // do extra processing for smartlines
  if (pageName == 'smartline') {
    mapLines = '&lines=' + mF.lines.value + '&classes=' + mF.classes.value;
    frameSrc = frameSrc + mapLines;
  }

  // ********************************************************
  // Get selected layers - if oz go through selected layers, get layers currently on map
  if (goTo == 'oz') {
    mapLayers = mf.layers;
    ll = mapLayers.length;
    layerText = '&layers=';
    for (i=0; i<ll; i++) {
      if (mapLayers[i].checked) layerText += mapLayers[i].value + ' '; 
    }
    // add report cards layers if required
    if (pageName == 'reportcards') {
	    ozReportCards();
    }
    // add habitats layers if required
    else if (pageName == 'habitats') {
	    ozHabitats();
    }
    // add smartline layers if required
    else if (pageName == 'smartline') {
	    ozSmartlines();
    }
  }  // goTo is OZ
  
  else {
    layerText = '&layers=' + mF.layers.value;
  }

  // Process user input
// ***************************************** OZ ***************
  if (goTo == 'oz') {
    setSelect();
    goTo = 'zoomin';
    frameSrc += '&mapext=' + mapfileExt;
    mFsrc.href = frameSrc + layerText; 
  }
  
  // ***************************************** ZOOM IN ***************
  else if (goTo == 'zoomin') {
    curExt = getBox();
    ext = curExt.split(' ');

    if (pageName == 'habitats') {
      zoominHabitats();
    }
    else if (pageName == 'reportcards') {
      zoominReportCards();
    }
    else if (pageName == 'smartline') {
      zoominSmartlines();
    }
    else {
      frameSrc += '&mapext=' + curExt;
    }

    mFsrc.href = frameSrc + layerText; 
  }
  
  // ***************************************** ZOOM OUT ***************
  else if (goTo == 'zoomout') {
    //setSelect();
    rb = mF.xy.value.split(' ');
    frameSrc += '&imgext=' + curExt + '&img.x=';
    frameSrc += (parseInt(rb[0])+parseInt(rb[2]))/2 + '&img.y=' + (parseInt(rb[1])+parseInt(rb[3]))/2 + '&zoom=-2';

    ext = curExt.split(' ');

    if (pageName == 'habitats') {
	    zoomoutHabitats();
    }
    else if (pageName == 'reportcards') {
	    zoomoutReportCards();
    }
    else if (pageName == 'smartline') {
	    zoomoutSmartlines();
    }

    mFsrc.href = frameSrc + layerText; 
  }
  
  // ***************************************** PAN ***************
  else if (goTo == 'pan') {
    setSelect();
    rb = mF.xy.value.split(' ');
    frameSrc += '&imgext=' + curExt + '&img.x=';
    frameSrc += (parseInt(rb[0])+parseInt(rb[2]))/2 + '&img.y=' + (parseInt(rb[1])+parseInt(rb[3]))/2;
    mFsrc.href = frameSrc + layerText; 

    if (pageName == 'habitats') {
	    panHabitats();
    }
    else if (pageName == 'reportcards') {
	    panReportCards();
    }
    else if (pageName == 'smartline') {
      panSmartlines();
    }

  }
  
  // ***************************************** INFO ***************
  else if (goTo == 'info') {
    // Set page url to map_results.jsp with box extents
    curExt = getBox();
	  
    if (pageName == 'smartline') {
	    infoSmartlines();
    }
    else if ((pageName == 'search') && (window.top.document.getElementById("gInfoSelected").value == 'beaches')) {
	    pageSrc = '/search_data/beach_list.jsp?pFormType=map&pLatLong=' + curExt;
      setGoTo('butt2','zoomin');
      window.top.location.href = pageSrc; 
    }
    else {  // other than smartline or search
      pageSrc = '/search_data/ozcoast_result.jsp?pFormType=map&pLatLong=' + curExt;
      setGoTo('butt2','zoomin');
      window.top.location.href = pageSrc; 
    }

   }
  
  // ***************************************** LEGEND ***************
  else if (goTo == 'legend') {
    // Open new window, call mapserver with map, map_web_template and layers
    pageSrc = mapservURL + '?map=' + mapFile + '&map_web_template=map_legend.html' + layerText + mapFilter;
    openWindow(pageSrc,'legend');
    goTo = 'zoomin'; 
  }

  // ***************************************** PRINT ***************
  else if (goTo == 'print') {
    // Open new window, call mapserver with map, map_web_template, map size & extents and layers
    pageSrc = mapservURL + '?map=' + mapFile + '&map_web_template=map_print.html&mapsize=700 490' + '&mapext=' + curExt + layerText + mapFilter;
    openWindow(pageSrc,'print');
    goTo = 'zoomin'; 
  }
  return false;
}

// **************************************************************************************************
// **************************************************************************************************
function zoominHabitats () {
	
  window.top.document.getElementById("gReportingRegion").value = "x";
  changeZoom(ext[2]-ext[0]);
  // do not include filter
  if (window.top.document.getElementById("gZoomLevel").value == "habitat") {
    frameSrc = mapservURL + '?map=' + mapFile + '&mapfile_ext=' + mapfileExt + '&mapext=' + curExt;
  }
  else {
    frameSrc += '&mapext=' + curExt;
  }
  updateRegionsMap("NAT", curExt);
	
}
// **************************************************************************************************
function zoominReportCards () {

  frameSrc += '&mapext=' + curExt;
  updateRegionsMap("NAT", curExt); 
  
}
// **************************************************************************************************
function zoominSmartlines () {
  
  if (window.top.document.getElementById("gCurrentSearch").value == "Stability") {
    window.top.document.getElementById("StabilityStatsFrame").src = 
                                                    window.top.document.getElementById("gCallStats").value + 
                                                    "pMbr=" + curExt +
                                                    "&pType=" + window.top.document.getElementById("pStabilityClasses").value;
  }
  else {
    window.top.document.getElementById("SmartlineListFrame").src = 
                                                    window.top.document.getElementById("gCallList").value + 
                                                    "pTheme=" + window.top.document.getElementById("pLandformTypes").value +
                                                    "&pGroupBy=" + window.top.document.getElementById("gGroupBy").value + 
                                                    "&pMbr=" + curExt;
  }
  
  frameSrc += '&mapext=' + curExt;
  
}
// **************************************************************************************************
function zoomoutHabitats () {
  
  diff = ext[2] - ext[0];
  window.top.document.getElementById("gReportingRegion").value = "x";
  changeZoom(diff*2);
  
  if (window.top.document.getElementById("gZoomLevel").value != "habitat") {
    filter = "&mapfiltername=map_grid50data_filter&mapfiltername2=map_grid10data_filter&mapfilter=(name='" 
               + window.top.document.getElementById("gHabitat").value + "')";
    frameSrc = frameSrc.replace('&mapfiltername=' + mF.mapfiltername.value + '&mapfiltername2=' + 
                                            mF.mapfiltername2.value + '&mapfilter=' + mF.mapfilter.value,
                                            filter);
  }
  
	mbr = getExtent(curExt, rb, 'zoomout');
	updateRegionsMap("NAT",mbr);
  
}
// **************************************************************************************************
function zoomoutReportCards () {
  
  mbr = getExtent(curExt, rb, 'zoomout');
	updateRegionsMap("NAT",mbr);
  
}
// **************************************************************************************************
function zoomoutSmartlines () {
  
  mbr = getExtent(curExt, rb, 'zoomout');
  if (window.top.document.getElementById("gCurrentSearch").value == "Stability") {
    window.top.document.getElementById("StabilityStatsFrame").src = 
                                            window.top.document.getElementById("gCallStats").value + 
                                            "pMbr=" + mbr +
                                            "&pType=" + window.top.document.getElementById("pStabilityClasses").value;  
  }
  else {
    window.top.document.getElementById("SmartlineListFrame").src = 
                                            window.top.document.getElementById("gCallList").value + 
                                            "pTheme=" + window.top.document.getElementById("pLandformTypes").value +
                                            "&pGroupBy=" + window.top.document.getElementById("gGroupBy").value + 
                                            "&pMbr=" + mbr;
  }
  
}
// **************************************************************************************************
function ozHabitats () {
  
  window.top.document.getElementById("gZoomLevel").value = "habitat";
  window.top.document.getElementById("gReportingRegion").value = "NAT";
  layerText += 'grid50data ';
  changeZoom(100);
  updateRegionsMap("NAT");
  
}
// **************************************************************************************************
function ozReportCards () {
  
  if (mF.mapfiltername.value == 'map_conditions_filter') {
	  layerText += 'conditions ';
  }
  else if (mF.mapfiltername.value == 'map_risks_filter') {
	  layerText += 'risks ';
  }
  updateRegionsMap("NAT", mapfileExt);
  
}
// **************************************************************************************************
function ozSmartlines () {
  
  layerText += ' ' + window.top.document.getElementById("gLayer").value + ' ';
  
}
// **************************************************************************************************
function panHabitats () {

  mbr = getExtent(curExt, rb, 'pan');
  // only recalculate if not at the most zoomed level (nothing to do)
  if (1==1) {
    //todo recalculate - after the calculations for the zooming functionality are done (not yet)
  }
  updateRegionsMap("NAT",mbr);
  
}
// **************************************************************************************************
function panReportCards () {
  
  mbr = getExtent(curExt, rb, 'pan');
	updateRegionsMap("NAT",mbr);
  
//  window.top.document.getElementById("gDisplayList").value = "false";
  
}
// **************************************************************************************************
function panSmartlines () {
  
  mbr = getExtent(curExt, rb, 'pan');
  if (window.top.document.getElementById("gCurrentSearch").value == "Stability") {
    window.top.document.getElementById("StabilityStatsFrame").src = 
                                              window.top.document.getElementById("gCallStats").value + 
                                              "pMbr=" + mbr +
                                              "&pType=" + window.top.document.getElementById("pStabilityClasses").value;  
  }
  else {
    window.top.document.getElementById("SmartlineListFrame").src = 
                                              window.top.document.getElementById("gCallList").value + 
                                              "pTheme=" + window.top.document.getElementById("pLandformTypes").value +
                                              "&pGroupBy=" + window.top.document.getElementById("gGroupBy").value + 
                                              "&pMbr=" + mbr;
  }
  
}
// **************************************************************************************************
function infoHabitats () {
  
  //
  
}
// **************************************************************************************************
function infoReportCards () {
  
  //
  
}
// **************************************************************************************************
function infoSmartlines () {
  
  ext = curExt.split(' ');
  mapSize = mapExt.split(' ');

  // must be zoomed in enough before can display information
  if ((mapSize[2]-mapSize[0]) < 0.5) {
    // can only select a small area to display information for
    if (((ext[2]-ext[0]) < 0.05) && ((ext[3]-ext[1]) < 0.05)) {
      var wintop = window.top.document.getElementById("LHS").offsetTop + 50;
      var winleft = window.top.document.getElementById("LHS").offsetLeft +
                         window.top.document.getElementById("LHS").offsetWidth-40;
      var settings = 'scrollbars,top='+ wintop + ',left='+winleft+
                          ',screenX=50,screenY=0,width=500'+',height=580,resizable=yes';
        
      pageSrc = "/coastal/smartline_popup.jsp?pMbr=" + curExt;
      winID = window.open(pageSrc,"Smartline", settings);
      winID.focus();
    }
    else {
      if (winID != null) {  
        if (!winID.closed) { 
          winID.close(); 
        } 
      }
      alert('Selected region too big, please select a smaller region to display information for.');
    }
      
  }  // zoomed enough
  else {
    alert('Zoom in more to display information about a line.');
    setGoTo('butt2','zoomin');
  }
  dragBoxDiv.style.visibility = 'hidden';
  
}
// **************************************************************************************************
// **************************************************************************************************

