﻿/// <reference path="../VEJS/VeJavaScriptIntellisenseHelper.js" />
var mapfind = null;
var mapdisplay = null;
var findPlaceResults = null;
var searchLocation = null;
var currentDisplayzoom = null;
var analShapeLayer = null;

function GetMaps() {



    if (mapfind == null) 
    {
        try {
            mapfind = new VEMap('myMap');
            mapfind.LoadMap(new VELatLong(53.5, -2.0), 6, 'h', false);
            mapfind.Resize(360, 500);
            mapfind.AttachEvent("ondoubleclick", MapSighting_OnDoubleClick);
      }
        catch (e) {
        }
    }

    if (mapdisplay == null)
            {
            try {
        mapdisplay = new VEMap('displayMap');
        mapdisplay.LoadMap(new VELatLong(53.5, -2.0), 6, 'h', false);
        mapdisplay.Resize(360, 500);
        mapdisplay.AttachEvent("ondoubleclick", MapDisplay_OnDoubleClick);
        mapdisplay.AttachEvent("onendzoom", MapDisplay_OnEndZoom);
        mapdisplay.AttachEvent("onendpan", MapDisplay_OnEndPan);
        mapdisplay.AttachEvent("onmouseover", map_onmouseover);
        
        currentDisplayzoom = mapdisplay.GetZoomLevel();
        analShapeLayer = new VEShapeLayer();
        mapdisplay.AddShapeLayer(analShapeLayer);
        showDocumentation();
        loadSummary();
        if (document.getElementById('hdnUserName').value != null) {
            getUserMapSummary();
        }
           }
           catch (e) {
         }
    }
}

function btnFindAddress() {
    //mapfind.ShowMessageBox = false;
    mapfind.Find(null, document.getElementById("TabContainer1_EnterSighting_txtAddress").value, null, null, null, null, true, true, null, true, GetCoordinates);
    return false;
}

function btnFindSearch() {
    //mapfind.ShowMessageBox = false;
    mapdisplay.Find(null, document.getElementById("TabContainer1_Overview_txtBoxSearchLocation").value, null, null, null, null, true, true, null, true, GetSearchCoordinates);
    return false;
}

function MapSighting_OnDoubleClick(e) {
    if (mapfind.GetShapeLayerByIndex(1) == null) {
        mapfind.AddShapeLayer(new VEShapeLayer());
    }
    var ll = mapfind.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
    PutWKTofPoint(ll.Latitude, ll.Longitude);
    var dblClickShape = new VEShape(VEShapeType.Pushpin, ll);
    dblClickShape.SetDescription('This is a new sighting yet to be saved');
    dblClickShape.SetTitle('New Sighting');
    dblClickShape.SetCustomIcon('images/SightingEntry.png');
    document.getElementById("TabContainer1_EnterSighting_txtAddress").value = 'location clicked';
    mapfind.GetShapeLayerByIndex(1).DeleteAllShapes();
    mapfind.GetShapeLayerByIndex(1).AddShape(dblClickShape);
    return true;
}
function MapDisplay_OnDoubleClick(e) {
    var ll = mapdisplay.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
    searchLocation = ll;
    PutWKTofPoint(ll.Latitude, ll.Longitude);
    //mapdisplay.Clear();
    var findPlace = new VEShape(VEShapeType.Pushpin, ll);
    findPlace.SetCustomIcon("<div><img src='images/QuestionMark.png'/></div>");
    mapdisplay.GetShapeLayerByIndex(1).DeleteAllShapes();
    mapdisplay.GetShapeLayerByIndex(1).AddShape(findPlace);
    document.getElementById('displayMapInfoResults').innerHTML = "Analysis Area"
    //getsearchinradius();
}
function GetSearchCoordinates(layer, resultsArray, places, hasMore, veErrorMessage) {

    findPlaceResults = places[0].LatLong;
    PutWKTofPoint(findPlaceResults.Latitude, findPlaceResults.Longitude);
    mapfind.GetShapeLayerByIndex(0).DeleteAllShapes();
    var myShape = new VEShape(VEShapeType.Pushpin, findPlaceResults);
    myShape.SetDescription('From address');
    myShape.SetTitle('From address');
    mapdisplay.AddShape(myShape);
}
function GetCoordinates(layer, resultsArray, places, hasMore, veErrorMessage) {
    if (mapfind.GetShapeLayerByIndex(1) == null) {
        mapfind.AddShapeLayer(new VEShapeLayer());
    }
    else {
        mapfind.GetShapeLayerByIndex(1).DeleteAllShapes();
    }
    findPlaceResults = places[0].LatLong;
    PutWKTofPoint(findPlaceResults.Latitude, findPlaceResults.Longitude);
    //mapfind.Clear();
    var myShape = new VEShape(VEShapeType.Pushpin, findPlaceResults);
    myShape.SetDescription('This is a new sighting yet to be saved');
    myShape.SetTitle('New Sighting');
    myShape.SetCustomIcon('images/SightingEntry.png');
    mapfind.GetShapeLayerByIndex(1).AddShape(myShape);
    //mapfind.AddShape(myShape);
}
function PutWKTofPoint(latitude, longitude) {
    document.getElementById("TabContainer1_EnterSighting_hdnfldLatitude").value = latitude;
    document.getElementById("TabContainer1_EnterSighting_hdnfldLongitude").value = longitude;
    return;
}

function getResultsInRadius() {
    var thisSearchLat = document.getElementById("TabContainer1_EnterSighting_hdnfldLatitude").value;
    var thisSearchLong = document.getElementById("TabContainer1_EnterSighting_hdnfldLongitude").value;
    var thisSearchRadius = document.getElementById("TabContainer1_Overview_txtBoxSearchRadius").value;
    if (thisSearchLat.length == 0) {
        return false;
    }
    if (thisSearchLong.length == 0) {
        return false;
    }
    if (thisSearchRadius.length == 0) {
        return false;
    }
    //km mile conversion if needed.
    var mileToKmConv = 1.609344;
    
    var e = document.getElementById("TabContainer1_Overview_drpDownKmMiles"); // select element
    var thisRadiusUnit = e.options[e.selectedIndex].value; 


    if (thisRadiusUnit == 'm') {
        thisSearchRadius = thisSearchRadius * mileToKmConv;
    }

    
   getsearchinradius(new VELatLong(thisSearchLat,thisSearchLong),thisSearchRadius );
    
    return false;
}
function loadSummary() {

    var view = mapdisplay.GetMapView();
    var south = view.BottomRightLatLong.Latitude;
    var west = view.TopLeftLatLong.Longitude;
    var north = view.TopLeftLatLong.Latitude;
    var east = view.BottomRightLatLong.Longitude

    if (south < 40.00) {
        south = 40;
    }
    if (west < -30.00) {
        west = -30;
    }
    if (north >70.00) {
        north = 70;
    }
    if (east > 30.00) {
        east = 30;
    }


    //Get the appropriate XMLHTTP object for the browser
    var xmlhttp = GetXmlHttp();

    // If we have a valid XMLHTTP object
    if (xmlhttp) {
        // Define the url of the handler
        var url = "Handlers/SummariseData.ashx";
        // Build the parameters that must be passed
        var params = "zoom=" + mapdisplay.GetZoomLevel() + "&north=" + north + "&south=" + south
        var params = params + "&east=" + east + "&west=" + west + "&maptype=VE";
        // Open the XmlHTTP request
        xmlhttp.open("GET", url + '?' + params, true);
        // Fire this when the readyState of the request changes
        xmlhttp.onreadystatechange = function() {
            // readystate 4 indicates that the request is complete  
            if (xmlhttp.readyState == 4) {
                // Read in the JavaScript response from the handler
                var result = xmlhttp.responseText;
                // Update the status message
                window.status = 'Loading Data...';
                try {
                    // Execute the dynamically created JavaScript
                    eval(result);
                    // Update the status message
                    window.status = 'Data Loaded!';
                }
                catch (e) {
                    // If the response cannot be evaluated
                    window.status = 'Data could not be loaded.';
                }
            }
        }
        // Send the XMLHttp Request
        xmlhttp.send(null);
    }
}

function getsearchinradius(searchLocation, searchradius) {


    //Get the appropriate XMLHTTP object for the browser
    var xmlhttp = GetXmlHttp();

    // If we have a valid XMLHTTP object
    if (xmlhttp) {
        // Define the url of the handler
        var url = "Handlers/GetSightingsNearLocation.ashx";
        // Build the parameters that must be passed
        var params = "lat=" + searchLocation.Latitude + "&long=" + searchLocation.Longitude + "&srchrad=" + searchradius;
        // Open the XmlHTTP request
        xmlhttp.open("GET", url + '?' + params, true);
        // Fire this when the readyState of the request changes
        xmlhttp.onreadystatechange = function() {
            // readystate 4 indicates that the request is complete  
            if (xmlhttp.readyState == 4) {
                // Read in the JavaScript response from the handler
                var result = xmlhttp.responseText;
                // Update the status message
                window.status = 'Loading Data...';
                try {
                    // Execute the dynamically created JavaScript
                    eval(result);
                    // Update the status message
                    window.status = 'Data Loaded!';
                }
                catch (e) {
                    // If the response cannot be evaluated
                    window.status = 'Data for radius search could not be loaded.';
                }
            }
        }
        // Send the XMLHttp Request
        xmlhttp.send(null);
    }
}
function getUserMapSummary() {
    //Get the appropriate XMLHTTP object for the browser
    var xmlhttp = GetXmlHttp();

    // If we have a valid XMLHTTP object
    if (xmlhttp) {
        // Define the url of the handler
        var url = "Handlers/GetUserRecords.ashx";
        // Build the parameters that must be passed
        var params = "owner=" + document.getElementById('hdnUserName').value;
        // Open the  request
        xmlhttp.open("GET", url + '?' + params, true);
        // Fire this when the readyState of the request changes
        xmlhttp.onreadystatechange = function() {
            // readystate 4 indicates that the request is complete  
            if (xmlhttp.readyState == 4) {
                // Read in the JavaScript response from the handler
                var result = xmlhttp.responseText;
                // Update the status message
                window.status = 'Loading Data...';
                try {
                    // Execute the dynamically created JavaScript
                    //alert(result);
                    eval(result);
                    // Update the status message
                    window.status = 'Data Loaded!';
                }
                catch (e) {
                    // If the response cannot be evaluated
                    window.status = 'Data could not be loaded.';
                }
            }
        }
        // Send the XMLHttp Request
        xmlhttp.send(null);
    }
}
function pop20kSquareDetails(osGridCentroid, osGridID, sqrsize, analPolygon) {
    //Get the appropriate XMLHTTP object for the browser
    var xmlhttp = GetXmlHttp();

    // If we have a valid XMLHTTP object
    if (xmlhttp) {
        // Define the url of the handler
        mapdisplay.GetShapeLayerByIndex(1).DeleteAllShapes();
        var url = "Handlers/GetOSGridData.ashx";
        // Build the parameters that must be passed
        var params = "osGridID=" + osGridID;
        var params = params + "&SquareSize=" + sqrsize;
        var params = params + "&osGridCentroid=" + osGridCentroid;
        // Open the  request
        xmlhttp.open("GET", url + '?' + params, true);
        // Fire this when the readyState of the request changes
        xmlhttp.onreadystatechange = function() {
            // readystate 4 indicates that the request is complete  
            if (xmlhttp.readyState == 4) {
                // Read in the JavaScript response from the handler
                var result = xmlhttp.responseText;
                // Update the status message
                window.status = 'Loading OS Grid Square Data';
                document.getElementById('displayMapInfoResults').innerHTML = 'Retrieveing data <image src=/"""images\progress_loading.gif/""">';
                try {

                    // Update the status message

                    window.status = 'OS Grid Square Data Loaded';
                    document.getElementById('displayMapInfoResults').innerHTML = result;
                    showInfo();
                    mapdisplay.GetShapeLayerByIndex(1).AddShape(analPolygon);
                    analPolygon.HideIcon();
                    analPolygon.SetZIndex(null, 800);
                    analPolygon.SetFillColor(new VEColor(250, 150, 0, 0.25));
                }
                catch (e) {
                    // If the response cannot be evaluated
                    window.status = 'OS Grid Square Data could not be loaded';
                }
            }
        }
        // Send the XMLHttp Request
        xmlhttp.send(null);
    }
}
function btnClearMapInfo_click() {
    showDocumentation();  
    return false;
}
function showInfo() {
    document.getElementById('displayMapInfo').className = 'viewResults';
    document.getElementById('displayMapInfoResults').className = 'viewResults';
    document.getElementById('displayMapInstructions').className = 'noviewDocumentation';
}
function showDocumentation() {
    document.getElementById('displayMapInfo').className = 'noviewResults';
    document.getElementById('displayMapInfoResults').className = 'noviewResults';
    document.getElementById('displayMapInstructions').className = 'viewDocumentation';
    mapdisplay.GetShapeLayerByIndex(1).DeleteAllShapes();
}
function setOtherVis() {
    var elemAreaDropDown = document.getElementById('TabContainer1_EnterSighting_DropDown_area');
    var myValue = elemAreaDropDown[elemAreaDropDown.selectedIndex].value;
    var elemOtherDiv = document.getElementById('sightingText_otherarea');
    if (myValue == 'o') {
        elemOtherDiv.style.display = 'block';
    }
    else {
        elemOtherDiv.style.display = 'none';
    }
    document.getElementById('TabContainer1').CssClass = 'mapTab';
}
function loggedOn() {
    EnableTab(4);
    EnableTab(5);
}

function checkDate(sender, args) {
    if (sender._selectedDate > new Date()) {
        alert("You cannot select a day later than today!");
        sender._selectedDate = new Date();
        // set the date back to the current date
        sender._textbox.set_Value(sender._selectedDate.format(sender._format));
    }
}
function btnSaveSighting_onClientClick() {
    document.getElementById('saveProgressSpan').style.visibility = 'visible';
    document.getElementById('TabContainer1_EnterSighting_lblSaveThanks').innerHTML= 'Saving, please wait';
    
    return true;
}
function ClusteringCallback(clusters) {
    //The function specified in the Callback must take an array of VEClusterSpecification Class objects.   
    try {
        if (clusters != null) {
            for (var i = 0; i < clusters.length; i++) {
                //VEClusterSpecification, http://msdn.microsoft.com/en-us/library/cc966730.aspx   
                //this has an array of your shapes that have been clustered .Shapes                   
                var cluster = clusters[i];

                //VEClusterSpecification.GetClusterShape();   
                //returns:A VEShape Class representing the pushpin cluster.    
                //Returns null if a VEClusterSpecification object was returned from the VEShapeLayer.GetClusteredShapes Method.   

                var clusterShape = clusters[i].GetClusterShape();

                var description = "This icon represents several Green City Bat projects. <br/><br/> Please zoom in to see further info or click the item in the list below. ";
                for (var s = 0; s < cluster.Shapes.length; s++) {

                    var shape = cluster.Shapes[s];

                    description += "<br/><a href='javascript:ShowPin(\"" + shape.GetID() + "\")'>" + shape.Title + "</a>";
                }
                //add back to the cluster shape
                clusterShape.SetDescription(description);
                clusterShape.SetTitle('Green City Bat Project Summary');
                clusterShape.SetCustomIcon('images/GreenParkMultiple.png');
            }
        }
    } catch (e) { alert(e.message); }
}
function ShowPin(pinID) {
    var pin = mapdisplay.GetShapeByID(pinID);
    if (pin != null)
        mapdisplay.ShowInfoBox(pin);
}  

