var osMap, boundaryLayer, screenOverlay, mapOV;

// Variables for gazetteer searches
var inputStr, globalGazArray, locationFound, o, da;

// Start of Functions required for gazetteer searches
//clear search box when clicked on
function clearText()
{
  document.getElementById("searchArea").value = "";
}

function searchGazetteer()
{
  //hide and clear list box
  document.getElementById('selectGaz').style.display = 'none';
  da = document.getElementById("selectGaz");
  da.options.length = 0;
  locationFound = 0;

  var query = document.getElementById("searchArea");
  inputStr = query.value;

  var osGaz = new OpenSpace.Gazetteer;
  var gazArray = osGaz.getLocations(inputStr, gazOptions);
}

function gazOptions(searchVal)
{
  //if one match found
  if (searchVal.length == 1)
  {
    if(searchVal[0].county == "Devon" || searchVal[0].county == "City of Plymouth"
      || searchVal[0].county == "Torbay")
    {
      osMap.setCenter(searchVal[0].location, 7);
      locationFound = 1;
    }
  }

  //if several choices, create a list box
  if (searchVal != null && searchVal.length > 1)
  {
    var dc = 0;

    globalGazArray = searchVal;
    o = document.createElement("OPTION");
    o.text = "Select a place";
    da.options.add(o);

    //build list box
    for (var i = 0; i < searchVal.length; i++)
    {
      o = document.createElement("OPTION");
      o.text = searchVal[i].name + ", " + searchVal[i].county;
      da.options.add(o);
      if(searchVal[i].county == "Devon" || searchVal[i].county == "City of Plymouth"
        || searchVal[i].county == "Torbay")
        ++dc;
    }

    if (dc)
    {
      locationFound = 1;
      //make list box visible
      document.getElementById('selectGaz').style.display = 'block';
    }
  }

  if (locationFound == 0)
    {
      document.getElementById("searchArea").value = "no such place in Devon";
    }
  else
    {
      document.getElementById("searchArea").value = "enter a place name";
    }
}

//zoom to item selected from list box
function zoomGazSel(selObj)
{
  osMap.setCenter(globalGazArray[selObj.selectedIndex-1].location, 7);

  //hide list box
  document.getElementById('selectGaz').style.display = 'none';

  //clear text field
  document.getElementById("searchArea").value = "enter a place name";
}


function init()
{
  // Create a new OS OpenSpace map object and pass it to our 'map' element id.
  // osMap = new OpenSpace.Map('map');
  // Enable 13 zoom levels, including 2 Vector Map layers (levels 4 and 2.5).
  var options = {resolutions: [2500, 1000, 500, 200, 100, 50, 25, 10, 5, 4, 2.5, 2]};
  osMap = new OpenSpace.Map('map', options);

  // Create a boundary layer with styling.
  boundaryLayer = createBoundaryLayer();

  // Create a new OpenLayers control without hover functionality.
  var hoverControl = new OpenLayers.Control.SelectFeature(boundaryLayer, {hover: false});

  // Add the control to the map and activate.
  osMap.addControl(hoverControl);
  hoverControl.activate();

  // Add the boundary layer to the map.
  osMap.addLayer(boundaryLayer);

  // Add another layer for displaying the grid position of the cursor
  var screenOverlay = new OpenSpace.Layer.ScreenOverlay("coords");
  screenOverlay.setPosition(new OpenLayers.Pixel(100, 60));
  osMap.addLayer(screenOverlay);

  // Add the gazetteer search box
  //define an overlay for search box
  searchBox = new OpenSpace.Layer.ScreenOverlay("search");
  //set its position
  searchBox.setPosition(new OpenLayers.Pixel(300, 0));
  // Add the search layer to the map.
  osMap.addLayer(searchBox);
  searchBox.setHTML(
    "<div id=\"OpenSpace.Layer.ScreenOverlay_132\" style=\"position: absolute; width: 200px; height: 100%; z-index: 340; left: 0px; top: 3px;\" class=\"olLayerDiv\">" +
    "<div id=\"div1\" style=\"z-index:999; padding-left: 0px; font-size: 14px;\">" +
    "<form name=\"searchForm\" style=\"border: none;\" onsubmit=\"return false;\">" +
    "<input type=\"text\" style=\"color:black; background-color: white;\" name=\"searchArea\" id=\"searchArea\" onclick=\"clearText()\" value=\"enter a place name\"/><input type=\"button\" style=\"color: black; background-color: white;\" onclick=\"searchGazetteer();\" value=\"Find\" title=\"find place in 1:50,000 gazetteer\"></button>" +
    "<select name=\"select\" id=\"selectGaz\" onchange=\"zoomGazSel(this.form.select)\" style=\"display: block\">" +
    "<option>Select a place</option><option></option></select></form></div>" +
    "</div>");
  //hide list box select
  document.getElementById('selectGaz').style.display = 'none';
  searchBox.events.register("mouseover", searchBox, function()
    {
      //de-activate keyboard and navigation controls
      osMap.controls[0].deactivate();
      osMap.controls[1].deactivate();
    }
  );
  searchBox.events.register("mouseout", searchBox, function()
    {
      //activate keyboard and navigation controls
      osMap.controls[0].activate();
      osMap.controls[1].activate();
    }
  );

  // Set the centre of the map.
  osMap.setCenter(new OpenSpace.MapPoint(265000, 092000), 3);

  // Display the cursor's grid postition as Easting/Northing
  var gridProjection = new OpenSpace.GridProjection();
  osMap.events.register("mousemove", osMap, function(e)
    {
      var pt = osMap.getLonLatFromViewPortPx(e.xy);
      screenOverlay.setHTML("<div style=\"width: 80px; color: black; background-color: white; font-size: 0.9em\">" +
        "E: " + pt.lon + "<br/>" +
        "N: " + pt.lat
      );
    }
  );
}

function createBoundaryLayer()
{
  // Set-up default symbolizer and a new style map.
  var symbolizer = OpenLayers.Util.applyDefaults({}, OpenLayers.Feature.Vector.style["default"]);
  var styleMap = new OpenLayers.StyleMap(symbolizer);

  // Define the custom styling.
  var lookup = {
  "CTY": {
    fillColor: "#CCFF99",
    fillOpacity: 0.2,
    strokeColor: "white",
    strokeWidth: 2,
    strokeOpacity: 0.8
    }
  };

  // Add rules to the style map.
  styleMap.addUniqueValueRules("default", "AREA_CODE", lookup);

  // Define the boundary layer with the strategies that are required (and with the above styling).
  var boundaryLayer = new OpenSpace.Layer.Boundary("Boundaries",
    {
    strategies:[new OpenSpace.Strategy.BBOX()],
    area_code:["CTY"],
    census_code:["18"],
    styleMap: styleMap
    }
  );

  return boundaryLayer;
}