﻿/// <reference path="VEJS/VeJavaScriptIntellisenseHelper.js" />

var map;
var latestResults;
var inQuery = false;

// Query by Text from button click
function buttonQuery_onclick() {
    if (inQuery == false) {
        inQuery = true;
        var search = document.getElementById("txtSearch").value;
        try {
            var ds = new Sys.Data.DataService(CFG_DATASERVICE);
            ds.query("GetMaoriLandByName?search='" + search + "'", cbSucess, cbFailure);
        } catch (ex) {
            alert("Problem encountered running query. Please refresh your browser." + ex);
        } 
    } else {
        alert("Running query, please wait...");
    }
}

// query by point from map mouse click
function MouseHandler(e) {
    if (e.eventName == "ondoubleclick") {
        if (inQuery == false) {
            inQuery = true;
            var pointwkt;
            var mode = map.GetMapMode();
            if (mode == VEMapMode.Mode2D) {
                var pixel = new VEPixel(e.mapX, e.mapY);
                var point = map.PixelToLatLong(pixel);
                pointwkt = "POINT(" + point.Longitude + " " + point.Latitude + ")";
            }
            else {
                pointwkt = "POINT(" + e.latLong.Longitude + " " + e.latLong.Latitude + ")";
            }
            try {
                var ds = new Sys.Data.DataService(CFG_DATASERVICE);
                ds.query("GetMaoriLandIntersectingPoint?point='" + pointwkt + "'", cbSucess, cbFailure);
                } catch(ex) {
                    alert("Problem encountered running query. Please refresh your browser.");
                }
        }else {
            alert("Running query, please wait...");
        }
        return true;
    } 
}

// put results into the listbox and select the first record for display
function cbSucess(result, context, operation) {
    latestResults = result;
    var rList = document.getElementById("resultList");
    var selected = rList.selectedIndex;
    rList.options.length = 0;
    for (var i in result) {
        var thisBlock = result[i];
        var li = document.createElement("option");
        li.appendChild(document.createTextNode(thisBlock.BlockName));
        rList.appendChild(li);
    }
    rList.selectedIndex = 0;
    visualiseFromList();
    inQuery = false;
}

function cbFailure(error, context, operation) {
    alert(error);
    inQuery = false;
}

// display the block details and render the shape in VE
function visualiseFromList(rList)
{
    var rList = document.getElementById("resultList");
    if (rList.selectedIndex != -1) {
        // display block geometry
        var selected = latestResults[rList.selectedIndex].Feature;
        map.DeleteAllShapes();
        visualise([selected]);

        // display block attributes
        var divBlockInfo = document.getElementById("blockInfo");
        var block = latestResults[rList.selectedIndex];
        divBlockInfo.innerHTML = "Name : " + block.BlockName + "<BR>" +
					 "Other Name : " + block.BlockAltName + "<BR>" +
                                         "District : " + block.BlockDistrictId + "<BR>" +
                                         "Area : " + block.BlockArea + "ha<BR>" +
                                         "Shares : " + block.TotalShares + "<BR>" +
                                         "Trust : " + block.Trust + "<BR>" +
                                         "Reservation : " + block.Reservation + "<BR>" +
                                         "Incorporation : " + block.Incorporation + "<BR>" +
                                         "Lease : " + block.Lease + "<BR>" +
                                         "Mortgage : " + block.Mortgage + "<BR>";
    }
}

// handle a click on the results listbox
function resultList_onclick() {
    visualiseFromList();
}

// setup the map, add the custom tile layer etc.
function pageLoad() {
	map = new VEMap("MapDiv");
	map.LoadMap(null, null, VEMapStyle.Road);
	map.AttachEvent("ondoubleclick", MouseHandler);
	map.AttachEvent("onendzoom", EndZoomHandler);
	map.AttachEvent("onendpan", EndZoomHandler);
//	map.ShowMiniMap(500, 10, VEMiniMapSize.Large);
    showMiniMap();
	map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
	map.EnableShapeDisplayThreshold(false);
	positionMap("New Zealand");
	GetTiles();
}

// turn the mini map on/off depending upon zoom 
function EndZoomHandler(e) {
    if(e.zoomLevel <= 9)
        map.HideMiniMap();
    else
        showMiniMap();
//        map.ShowMiniMap(500, 10, VEMiniMapSize.Large);
}

function showMiniMap() {
    var mapWidth = document.getElementById("MapDiv").offsetWidth;
    
    map.ShowMiniMap(mapWidth - 205, 10, VEMiniMapSize.Large);
    //map.ShowMiniMap(500, 10, VEMiniMapSize.Large);
}

// function to position the viewport of the map.  Set the coordinates to 
// the bounding box you want to display.
function positionMap(location) {
    if (location == "New Zealand") {
        map.SetMapView(new VELatLongRectangle(new VELatLong(-37.4, 172.86),
                                                new VELatLong(-46.42, 179.48),
                                                new VELatLong(-37.4, 179.48),
                                                new VELatLong(-46.42, 172.86)));
    }
    if (location == "North Island") {
        map.SetMapView(new VELatLongRectangle(new VELatLong(-37.4, 172.86),
                                                new VELatLong(-40.13, 179.48),
                                                new VELatLong(-37.4, 179.48),
                                                new VELatLong(-40.13, 172.86)));
    }
    if (location == "South Island") {
        map.SetMapView(new VELatLongRectangle(new VELatLong(-41.25, 164.48),
                                                new VELatLong(-46.42, 177.75),
                                                new VELatLong(-41.25, 177.75),
                                                new VELatLong(-46.42, 164.48)));
    }
    if (location == "Chatham Islands") {
        map.SetMapView(new VELatLongRectangle(new VELatLong(-43.69, -177.4),
                                                new VELatLong(-44.33, -175.81),
                                                new VELatLong(-43.69, -175.81),
                                                new VELatLong(-44.33, -177.4)));
    }

}

// set the tileSourceSpec to the public URL for the tile service.  This will be called from the
// users browser
function GetTiles() {
    var bounds = [new VELatLongRectangle(new VELatLong(80, -180), new VELatLong(-80, 180))];
    //var tileSourceSpec = new VETileSourceSpecification("tpktiles", "http://s-dev-maoriland/GetMap.tile?quadkey=%4&boarder=true&render=true&attributes=true");
    var tileSourceSpec = new VETileSourceSpecification("tpktiles", CFG_TILESERVICE);
    tileSourceSpec.NumServers = 4;
    tileSourceSpec.Bounds = bounds;
    tileSourceSpec.Opacity = 0.7;
    map.AddTileLayer(tileSourceSpec, true);
}  


// parse the well know text attribute and create shapes in VE
function visualise(ShapesArray) {

	var pointsArray;
	var shape;

	try {
	    for (var i = 0; i < ShapesArray.length; i++) {

	        if (ShapesArray[i].length > 0) {
	            if (ShapesArray[i].search(/^ *POLYGON/i) != -1) {
	                pointsArray = drawShape(ShapesArray[i], /^ *POLYGON *\(\(/i, / *\)\) */);
	                shape = new VEShape(VEShapeType.Polygon, pointsArray);
	                shape.SetLineWidth(3);
			shape.HideIcon();
	                shape.SetLineColor(new VEColor(255, 0, 0, 1.0));
	                shape.SetFillColor(new VEColor(0, 0, 0, 0.0));
	            }
	            else if (ShapesArray[i].search(/^ *POINT/i) != -1) {
	                pointsArray = drawShape(ShapesArray[i], /^ *POINT *\(/i, / *\) */);
	                shape = new VEShape(VEShapeType.Pushpin, pointsArray);
	            }
	            else if (ShapesArray[i].search(/^ *LINESTRING/i) != -1) {
	                pointsArray = drawShape(ShapesArray[i], /^ *LINESTRING *\(/i, / *\) */);
	                shape = new VEShape(VEShapeType.Polyline, pointsArray);
			shape.HideIcon();
	            }
	            else if (ShapesArray[i].search(/^ *MULTIPOLYGON/i) != -1) {

	                ShapesArray[i] = ShapesArray[i].replace(/\)\)\,/g, ")) |POLYGON");
	                ShapesArray[i] = ShapesArray[i].replace("MULTIPOLYGON", "|POLYGON");
	                ShapesArray[i] = ShapesArray[i].replace(/\(\(\(/, "((");
	                ShapesArray[i] = ShapesArray[i].replace(/\)\)\)/, "))");
	                var polygons = ShapesArray[i].split(/\|/);
	                visualise(polygons);
	                return;
	            }
	            else {
	                alert('Feature is too complex to display.');
	                return;
	            }

	            map.AddShape(shape);

	            if (i == 0) {
	                map.SetMapView(shape.GetPoints());
	            }
	        }
	    }
	} catch (ex) {
	    alert("Feature cannot be displayed." + ex);
	}
}

// helper function used by visualise() 
function drawShape(ShapeString, StartRegex, EndRegex) {

	var shapeArray = cleanupWKT(ShapeString, StartRegex, EndRegex);	
	
	var pointsArray = new Array();
	var tempLatLon;

	for (var i=0; i<shapeArray.length; i++)
	{
	    tempLatLon = shapeArray[i].split(/ /);
	    if (tempLatLon[0] > 180)
	        tempLatLon[0] = (360 - tempLatLon[0]) * -1;
		pointsArray[i] = new VELatLong(parseFloat(tempLatLon[1]), parseFloat(tempLatLon[0]));   //wkt is long lat
	}
	
	return pointsArray;	
}

// helper function used by visualise() 
function cleanupWKT(ShapeString, StartRegex, EndRegex) {

      var cleanedString = ShapeString.replace(StartRegex, "");
      cleanedString = cleanedString.replace(EndRegex, "");
      var shapeArray = cleanedString.split(", ");

      return shapeArray;
}
