/// <reference name="MicrosoftAjax.js"/>


function fullExtent(){


            //var startExtent = new esri.geometry.Extent(375000, 504000, 450000, 559000, new esri.SpatialReference({ wkid: 27700 }) );            
	  

	    //map.setExtent(startExtent, true);

	    navToolbar.zoomToFullExtent();


}

function PostCodeKeyDown(e)
{
     var key;

     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox


   var boolVal = true;

   if (key==13){

        var postcode = document.getElementById('txtpostcode').value;
       
       if (postcode != "")
       {    

        postcodeSearch(postcode);
       }    

       boolVal = false;
    }  
  return boolVal; 
  
}


function doPostCodeSearch()
{
  
   var postcode = document.getElementById('txtpostcode').value;
  if (postcode != "")
  {
   postcodeSearch(postcode);
  }
 
}



function setEnvelope_FindPlace(dropDown) {

    // get drop down reference
    var selectedExtentString = dropDown.options[dropDown.selectedIndex].value;

    if (selectedExtentString != "") {

        // get extent from string
        var extent = selectedExtentString.split(',');

        if (extent.length == 4) {

            var xmin = 0;
            var ymin = 0;
            var xmax = 0;
            var ymax = 0;

            try {
                xmin = parseInt(extent[0]);
                ymin = parseInt(extent[1]);
                xmax = parseInt(extent[2]);
                ymax = parseInt(extent[3]);
            }
            catch (exception) {

                alert('Unable to create extent.');
            }

            // set extent on map
            var newExtent = new esri.geometry.Extent();
            var spatialRef = new esri.SpatialReference({ wkid: 27700 });

            newExtent.xmin = parseFloat(xmin);
            newExtent.ymin = parseFloat(ymin);
            newExtent.xmax = parseFloat(xmax);
            newExtent.ymax = parseFloat(ymax);
            newExtent.spatialReference = spatialRef;

            map.setExtent(newExtent, true);
        }
    }
}

function showExtent(ext) {

    // update scale
    dojo.byId("Scale").innerHTML = "<span class='txtxys'>Map Scale: </span>1:" + parseInt(map.getScale()); //"Map Scale: "
}

function showCoordinates(evt) {

    //get mapPoint from event
    var mp = evt.mapPoint;
    //display mouse coordinates
    dojo.byId("info").innerHTML = "<span class='txtxys'>Map Coordinates: </span>" + parseInt(mp.x) + ", " + parseInt(mp.y); //"Map Coordinates: " +
}

function populateParishList(featureSet) {

    // move featureSet results into standard string array. Then use sort function to reorder the array in alphabetical order
    var arrTexts = new Array();

    for (var i = 0, il = featureSet.features.length; i < il; i++) {

        var feat = featureSet.features[i];
        var parishName = feat.attributes.PAR_NAME;
        arrTexts[i] = parishName;
    }

    arrTexts.sort();

    // get parish drop down list reference
    var ddl = document.getElementById('SelectParishSearch');
    
    // populate drop down list with string array
    for (var i = 0, il = arrTexts.length; i < il; i++) {

        var name = arrTexts[i];
        var theOption = new Option;
        theOption.text = name;
        theOption.value = name;
        ddl.options[i + 1] = theOption;

    }

    // add handler to change map extent to selected parish extent
    // ddl.onchange = getParish;
}

function getParish() {

    // use query task to find extent of selected parish
    var ddl = document.getElementById('SelectParishSearch');
    var selectedParish = ddl.options[ddl.selectedIndex].value;

    if (selectedParish != '') {

        var selectedQueryParish = new esri.tasks.Query();
        selectedQueryParish.returnGeometry = true;
        selectedQueryParish.outFields = ["PAR_NAME"];
        selectedQueryParish.where = "PAR_NAME = '" + selectedParish + "'";

        queryTaskParish.execute(selectedQueryParish, navigateToParish);
    }
}

function navigateToParish(feature) {

    // set map with parish extent
    var feature = feature.features[0];
    var extent = feature.geometry.getExtent();
    map.setExtent(extent, true);
}

function executeQueryTask(evt) {

    if(parseInt(map.getScale()) <= 10000)
    {

    		// get user click info
    		mapIdentifyX = evt.mapPoint.x;
    		mapIdentifyY = evt.mapPoint.y;

    		var centerPoint = new esri.geometry.Point(evt.mapPoint.x, evt.mapPoint.y, evt.mapPoint.spatialReference);
    		var mapWidth = map.extent.getWidth();

    		// divide width in map units by width in pixels
    		var pixelWidth = mapWidth / map.width;

    		// calculate a 10 pixel envelope width (5 pixel tolerance on each side)
    		var tolerance = 5 * pixelWidth;

    		// build tolerance envelope and set it as the query geometry
    		var queryExtent = new esri.geometry.Extent
                (1, 1, tolerance, tolerance, evt.mapPoint.spatialReference);
    
    		var queryTask = new esri.tasks.QueryTask("http://spatial.durham.gov.uk/ArcGIS/rest/services/External/PROW/MapServer/0");

       		// set up queries
    		var query = new esri.tasks.Query();
    		query.returnGeometry = true;
    		query.outFields = ["STATUS", "PARISH", "PROW_NO__F", "PROW_UNIQU"];
    		query.geometry = queryExtent.centerAt(centerPoint);

    		// execute task and call showResults on completion
    		queryTask.execute(query, showResults);

    }
    else
    {
		alert('Sorry, you are unable to use the identify tool at this scale level. Please zoom to a scale of at least 1:10,000 or below.');
    }

}

function showResults(featureSet) {
    
    // clear map
    map.graphics.clear();
    map.infoWindow.hide();
    var geometry = null;

    for (var i = 0, il = featureSet.features.length; i < il; i++) {
    
        // get the current feature from the featureSet.
        var graphic = featureSet.features[0];
        graphic.setSymbol(symbol);

        // set the infoTemplate.
        graphic.setInfoTemplate(infoTemplate);

        // add graphic to the map graphics layer.
        map.graphics.add(graphic);

        // set infowindow text
        map.infoWindow.setContent(graphic.getContent());
        map.infoWindow.setTitle(graphic.getTitle());
        geometry = graphic.geometry;

    }

    if (featureSet.features.length != 0) {

        // show infowindow
        var point = new esri.geometry.Point(mapIdentifyX, mapIdentifyY);
        map.infoWindow.show(map.toScreen(point), map.getInfoWindowAnchor(map.toScreen(point)));
    }

}


function ButtonIdentify_onclick() {

    // set to pan to prevent zoom
    navToolbar.activate(esri.toolbars.Navigation.PAN);

    // change mouse cursor
    map.setMapCursor("pointer");
    
    // listen for click event on the map
    identifyHandle = dojo.connect(map, "onClick", executeQueryTask);
}


function ButtonClearGraphics_onclick() {

    // set to pan to prevent zoom
    navToolbar.activate(esri.toolbars.Navigation.PAN);

    map.setMapCursor("default");

    // clear map display
    map.infoWindow.hide();
    map.graphics.clear();
}

function postcodeSearch(postcode) {

 
    
    // call web service
  
    PostCodeWS.PostCodeWebService.FindPostcodeExtent(postcode, navigateToExtent, onFailure);

}

function navigateToExtent(result) {



    if (result == '') {
        alert('Invalid Postcode Format');
    }
    else {
        // get extent from result string
        var extent = result.split(',');
        if (extent.length == 4) {

            var xmin = 0;
            var ymin = 0;
            var xmax = 0;
            var ymax = 0;

            try {
                xmin = parseInt(extent[0]);
                ymin = parseInt(extent[1]);
                xmax = parseInt(extent[2]);
                ymax = parseInt(extent[3]);
            }
            catch (exception) {

                alert('Unable to create extent.');
            }

            var newExtent = new esri.geometry.Extent();
            var spatialRef = new esri.SpatialReference({ wkid: 27700 });

            newExtent.xmin = parseFloat(xmin);
            newExtent.ymin = parseFloat(ymin);
            newExtent.xmax = parseFloat(xmax);
            newExtent.ymax = parseFloat(ymax);
            newExtent.spatialReference = spatialRef;

            // set map extent
            map.setExtent(newExtent, true);
        }
        else {
            alert('Invalid Extent');
        }
    }
}

function onFailure(result) {

    // error handle
    alert("Error Invoking the Web Service.");
}
