﻿var _shapeFillColor_Default = new VEColor( 0, 0, 255, 0.2 );	//blue
var _shapeFillColor_Highlight = new VEColor( 255, 255, 0, .2 ); // yellow
var _shapeLineColor_Default = new VEColor( 0, 0, 255, 0.5 );    //blue line
var _shapeLineColor_Highlight = new VEColor( 185, 0, 0, 0.5 );    //red line
var _shapeLineColor_Error = new VEColor( 185, 0, 0, 0.6 );		//black line
var _geoRssLayer = new VEShapeLayer();
var _geoRssFillColor_Default = new VEColor(51, 0, 51, .2); // plum
var _geoRssLineColor_Default = new VEColor(51, 0, 51, .6); // plum
var _geoRssLineWidth = 2;
// #####################################
// ########## Shape Functions ##########
// #####################################
var _shapeCount = 0;
var _shapeBeingDrawn = null;


function ShapeListSelect(shape, state)
{
	 // Select shape from list
	var shapeTitle = shape.GetTitle();
	var listbox = document.getElementById("lstShapes");
	//alert(listbox.options.length);
	for(i=0; i<listbox.options.length; i++)	
	{
		//alert(listbox.options[i].text);
		if(shapeTitle == listbox.options[i].text)
		{
                   		listbox.options[i].selected = state;
		}
	}
}

function SelectShape(shape)
{
    _shapeSelectedShapes.push(shape)

    shape.SetFillColor(_shapeFillColor_Highlight)
	shape.SetLineColor(_shapeLineColor_Highlight)
	//select this value in the shape list
	ShapeListSelect(shape, true);
	deleteListings();
}

function DeselectShape(shape)
{
    for (var i = 0; i < _shapeSelectedShapes.length; i++) {
        if (_shapeSelectedShapes[i].GetTitle() == shape.GetTitle())
            _shapeSelectedShapes.splice(i, 1); 
    }   
    
    // Set fill color based on shape layer
    var layer = shape.GetShapeLayer();
    if (typeof(_geoRssLayer)!="undefined")
    {
        if (layer == _geoRssLayer)
        {
            shape.SetFillColor(_geoRssFillColor_Default)
            shape.SetLineColor(_geoRssLineColor_Default)
        }
        else
        {
            shape.SetFillColor(_shapeFillColor_Default)
            shape.SetLineColor(_shapeLineColor_Default)
        }
    }
    //de-select this value in the shape list
    ShapeListSelect(shape, false);
}

function IsSelected(shape)
{
    // Loop through all selected shapes
    var shapeCount = _shapeSelectedShapes.length;
    for(var shapeCounter = 0 ; shapeCounter < shapeCount; shapeCounter++)
    {
        // Check to see if this shape matches the requested shape
        if (_shapeSelectedShapes[shapeCounter] == shape)
        {
            return true;
        }
    }
}

function DeselectAllShapes(layer)
{
    // Loop through all shapes in this layer and deselect
    var shapeCount = layer.GetShapeCount();
    for(var shapeCounter = 0 ; shapeCounter < shapeCount; shapeCounter++)
    {
        var shape = layer.GetShapeByIndex(shapeCounter);
        DeselectShape(shape);
    }

    // Reinitialize array
    _shapeSelectedShapes = new Array();
}

function GetShapes(shapeTypeId)
{	
    clearShapeLayers();
    displaySearchingImage();
    
	if(_map.GetMapStyle()==VEMapStyle.Birdseye){
		ShowListingSearchWarning('Boundaries are not available in Birds Eye view');
		return;
	}

    // Check zoom level
	if (_map.GetZoomLevel() < 10)
	{
		ShowListingSearchWarning("Please zoom in closer to view boundaries.");
		zoomIn('setTimeout(\"GetShapes(\''+shapeTypeId+'\')\",500)');
		return;
	}

    var request = InitHttpRequest();
    
    // AJAX return function
    // Get XML document containing shapes
    request.onreadystatechange = function()
    {         
	    if (request.readyState == 4)
	    {
		    if (request.status == 200)
		    {
                ShowShapes(request.responseText);
		    }	
		    else	
		    {
			    alert("Error: returned status code " + request.status + " " + request.statusText);
		    }	
	    } 
    }

    // Open http request and set header
    request.open("POST", "../WebServices/ShapeSearch.ashx", true); 
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Set search parameters
    var mapView = _map.GetMapView();
    var latitudeMin = mapView.BottomRightLatLong.Latitude;
    var longitudeMin = mapView.TopLeftLatLong.Longitude;
    var latitudeMax = mapView.TopLeftLatLong.Latitude;
    var longitudeMax = mapView.BottomRightLatLong.Longitude;

//    // Get a comma delimited list of existing shape titles in this layer
//    var shapeTitles = "";
//    for(var shapeCounter = 0 ; shapeCounter < _geoRssLayer.GetShapeCount(); shapeCounter++)
//    {
//        var shape = _geoRssLayer.GetShapeByIndex(shapeCounter);
//        shapeTitles += shape.GetTitle() + ",";
//    }
//    shapeTitles = shapeTitles.slice(0, shapeTitles.length - 1)
	
    // Build query string for HTTP request
    var queryString = 
        "ShapeTypeId=" + shapeTypeId
        + "&LatitudeMin=" + latitudeMin 
        + "&LongitudeMin=" + longitudeMin 
        + "&LatitudeMax=" + latitudeMax 
        + "&LongitudeMax=" + longitudeMax;
//        + "&Shapes=" + shapeTitles;
        
    // Submit http request
    document.getElementById("divResult").innerHTML = "WebServices/ShapeSearch.ashx?" + queryString;
    request.send(queryString);
}

function ShowShapes(textObject)
{
    var geoShapeCount = textObject.substring(0,6);
    
    if (geoShapeCount > 100)
    {
        ShowListingSearchWarning("<span style=\"font-size:1.2em;font-weight:bold;color:red;margin-left:3px;\">"+parseFloat(geoShapeCount)+"</span><span style=\"color:red;\"> matching shapes.<br />&nbsp;Please zoom in</span>");
        deleteListings();
        return;
    }
    
       // Check to see if listing layer exists
    if (typeof(_geoRssLayer)!="undefined")
    {
        // Delete all existing listing icons
        _geoRssLayer.DeleteAllShapes();       
    }
    else
    {
        // Create listing layer
        _geoRssLayer = new VEShapeLayer();
        _map.AddShapeLayer(_geoRssLayer);
    }
    
    var geoShapes = textObject.substring(6,textObject.length).split("@^");   //make an array of shapes
    var elementCount = parseFloat(geoShapeCount);
    
     //show data: for debugging
    for (var n = 0, len = geoShapes.length, shapeItems; n < len; n++) {
        document.getElementById('divResult').innerHTML += geoShapes[n]+"<br><br>";
       }
       
	// Display number of found shapes
	displayMatching("<span style=\"font-size:1.4em;font-weight:bold;color:green;margin-left:3px;\">" + elementCount+ "</span> matching shapes");

	var shapeArray = [];
	for (var n = 0, len = geoShapes.length, shapeItems; n < len; n++) {
		if(geoShapes[n]) {								//take a single school: shapeElements[n]
			shapeItems = geoShapes[n].split("@~"); 	    //make an array of its properties
			
			var boundary = new Boundary();                  //Populate a ve_shape_object
   		    boundary.Populate(shapeItems);
   		    //shapeArray.push(boundary.GetShape());

   		    _geoRssLayer.AddShape(boundary.GetShape()); //Adding manually for now....

		}
	} 
	//THIS NOT WORKING FOR SOME REASON ON BOUNDARY FILES
	//if(shapeArray.length > 0) {
    //    boundary.DisplayShapeArray(shapeArray);               //Display shapes on map
    //}
    UpdateShapeList();
}	

function UpdateShapeList()
{  
    var shapes = new Array();
    var listIndex = 0;
	
    // Initialize drop down list
    document.getElementById("lstShapes").options.length = 0;    
	
	// Check to see if the draw layer exists
//	var drawShapeTitles = new Array();
//	if(typeof _drawLayer != 'undefined')
//	{
//        var shapeTitles = new Array();

//		// Loop through all shapes in this layer
//        var shapeCount = _drawLayer.GetShapeCount();
//        for(var shapeCounter = 0; shapeCounter < shapeCount; shapeCounter++)
//        {
//            // Add shape title and shape object to arrays
//            var shape = _drawLayer.GetShapeByIndex(shapeCounter);
//            shapeTitles.push(shape.GetTitle());
//            shapes.push(shape)            
//        }

//        // Sort shape titles
//        shapeTitles.sort();

//        // Add draw layer shapes to list
//        for(var shapeTitleCounter = 0; shapeTitleCounter < shapeTitles.length; shapeTitleCounter++)
//        {
//            // Add item to list
//            var shapeTitle = shapeTitles[shapeTitleCounter];
//            document.getElementById("lstShapes").options[listIndex] = new Option(shapeTitle, "Draw:" + shapeTitle);
//            if (IsSelected(shapes[listIndex]))
//            {
//                // Select shape from list
//                document.getElementById("lstShapes").options[listIndex].selected = true;
//            } 
//                               
//            listIndex++;
//        }
//	}
		
	// Check to see if the georss layer exists
	if(typeof _geoRssLayer != 'undefined')
	{
        var shapeTitles = new Array();

		// Loop through all shapes in this layer
        var shapeCount = _geoRssLayer.GetShapeCount();
        for(var shapeCounter = 0; shapeCounter < shapeCount; shapeCounter++)
        {
            // Add shape title and shape object to arrays
            var shape = _geoRssLayer.GetShapeByIndex(shapeCounter);
            shapeTitles.push(shape.GetTitle());
            shapes.push(shape)            
        }

        // Sort shape titles
        shapeTitles.sort();

        // Add georss layer shapes to list
        for(var shapeTitleCounter = 0; shapeTitleCounter < shapeTitles.length; shapeTitleCounter++)
        {
            // Add item to list
            var shapeTitle = shapeTitles[shapeTitleCounter];
            document.getElementById("lstShapes").options[listIndex] = new Option(shapeTitle, "GeoRss:" + shapeTitle);
            if (IsSelected(shapes[listIndex]))
            {
                // Select shape from list
                document.getElementById("lstShapes").options[listIndex].selected = true;
            } 
                               
            listIndex++;
        }
	}
}


// layerShapeCombo = layerName + ":" + shapeTitle
function ZoomToShape(layerShapeCombo)
{
    // Parse index into separate shape and layer indices
    var keys = new Array(); // array of alternating layer and shape index values
    keys = layerShapeCombo.split(":");
    var layerName = keys[0];
    var shapeTitle = keys[1];
    
    // Get layer
    var layer = null;// VELayer object
    switch(layerName)
    {
        case "Draw":
            layer = _drawLayer;
            break;
        case "GeoRss":
            layer = _geoRssLayer;
            break;
    }

    // Get shape
    var shape = null; // VEShape object
    for(var shapeCounter = 0 ; shapeCounter < layer.GetShapeCount(); shapeCounter++)
    {
        shape = layer.GetShapeByIndex(shapeCounter);
        
        // Check to see if this is the shape we want...if so, then exit the loop
        if (shape.GetTitle() == shapeTitle)
            break;
    }
        
    //Deselect all shapes in polygon layers
	if(typeof _drawLayer != 'undefined') {
		DeselectAllShapes(_drawLayer);
		}
	if(typeof _geoRssLayer != 'undefined') {
		DeselectAllShapes(_geoRssLayer);
		}
		
    _map.SetMapView(shape.GetPoints());

    SelectShape(shape)
}

function DeleteShape(shapeID)
{
    if(document.getElementById("divShapeHover") != 'undefined') {
		document.getElementById("divShapeHover").style.display = "none";
	}

    var shape = _drawLayer.GetShapeByID(shapeID);
    DeselectShape(shape)

	_drawLayer.DeleteShape( shape );
}
