Shape = {};

var points = null;
var tempPoints = null;
var num = 0;  
var tempShape = null;
var startPin = null;
var shape = null;
var polyLayer = null;
var polyLayer2 = null;
var startPointSet = null;
var zoomToShape = false;
function initalize()
{
    points = new Array();
    tempPoints = new Array();
    startPointSet = 0;
}
Shape.DrawPolygon = function(polyPoints) // comma delimited string
{
    var arrPoints = polyPoints.split(',');
    var arrLatLong = new Array();
    var ctr=0;
    for (var i=0;i<arrPoints.length/2;i++)
    {
        arrLatLong[i] = new VELatLong(parseFloat(arrPoints[ctr]),parseFloat(arrPoints[ctr+1]));
        ctr=ctr+2;
    }
    if (polyLayer == null)
    {
        polyLayer = new VEShapeLayer();
        veMap.AddShapeLayer(polyLayer);
    }

    drawPolygon(arrLatLong);
    display('draw_clear');
    hide('draw_start');
}
Shape.StartDrawing = function() 
{
    initalize();
    document.getElementById('PolygonType').value = 'custom';
    hide('draw_start');
    display('draw_cancel');
    display('draw_clear');
    if (polyLayer == null)
    {
        polyLayer = new VEShapeLayer();
        veMap.AddShapeLayer(polyLayer);
    }
    //else
    //    polyLayer.DeleteAllShapes();
    
    //delete all pins
    pushpin.deleteAllPins();
    if (polyLayer2) // delete any boundaries
        polyLayer2.DeleteAllShapes();
    if (document.getElementById('selNeighborhood')) // clearout neighborhood selection
    {
        document.getElementById('selNeighborhood').value = "";
        document.getElementById('Neighborhood').selectedIndex = 0;
    }            
    document.getElementById('divMap').style.cursor = 'crosshair';
    veMap.AttachEvent('onclick', mapDrawingClick);
    veMap.AttachEvent('onmousemove', mapDrawingMouseMove);
    veMap.vemapcontrol.EnableGeoCommunity(true);
    
    //display tip
    display('divDrawingTips');
    displayDrawingTip(1);
}        
function mapDrawingClick(e) 
{
    points.push(GetClickLatLong(e));
}        
function drawPolygon(points)
{
    shape = new VEShape(VEShapeType.Polygon, points);
    shape.SetFillColor(new VEColor(131, 185, 187, 0.1));
    shape.SetLineColor(new VEColor(98, 173, 201, 1.0)); 
    shape.SetLineWidth(2);
    shape.HideIcon();
    
    hide('draw_cancel');
    //display('draw_start');
    try 
    {
        polyLayer.DeleteAllShapes();
        //polyLayer.DeleteShape(tempShape);
        //polyLayer.DeleteShape(startPin);
    }
    catch (err) {}
    polyLayer.AddShape(shape);  
    
    // set point value
    document.getElementById('PolyPoints').value = points;

}

Shape.EndDrawing = function() {
    points.push(points[0]);
    drawPolygon(points);

    // center polygon
    //veMap.SetMapView(points);

    DetachDrawingEvents();
    if (zoomToShape) {
        veMap.SetMapView(points);
        if (document.getElementById('PolyCenLat'))
            document.getElementById('PolyCenLat').value = veMap.vemapcontrol.GetCenterLatitude();
        if (document.getElementById('PolyCenLon'))
            document.getElementById('PolyCenLon').value = veMap.vemapcontrol.GetCenterLongitude();
    }
    //map.submitSearch(); // get listings in shape    
}
Shape.CancelDrawing = function() {
    DetachDrawingEvents();
    hide('draw_cancel');
    display('draw_start');
    if (document.getElementById('PolyPoints').value == '') {
        hide('draw_clear');
    }
    try {
        points = new Array();
        polyLayer.DeleteShape(tempShape);
        polyLayer.DeleteShape(startPin);
        map.submitSearch();
    }
    catch (err) { }
}
Shape.ClearDrawing = function()   
{
    hide('draw_clear');
    display('draw_start');
    try 
    {
        initalize();
        polyLayer.DeleteAllShapes();
    }
    catch (err) {}
    
    // only resubmit search if there was a polygon previously drawn
    if (document.getElementById('PolyPoints').value != '') 
    {
       document.getElementById('PolyPoints').value = '';
       document.getElementById('PolygonType').value = '';
       map.submitSearch(); // get all listings
    }
}
function mapDrawingMouseMove(e) 
{
    tempPoints = points.slice(0, points.length);
    tempPoints.push(GetClickLatLong(e));  
    
    try
    {
        polyLayer.DeleteShape(tempShape);
    }
    catch (err){}
    try
    {
        
        if(tempPoints.length < 3)
        {
            tempShape = new VEShape(VEShapeType.Polyline, tempPoints);
        }
        else
        {
            tempShape = new VEShape(VEShapeType.Polygon, tempPoints);
        }
        tempShape.SetFillColor(new VEColor(153, 153, 153, 0.4));
        tempShape.SetLineColor(new VEColor(153, 153, 153, 1.0));
        tempShape.SetLineWidth(2);
        tempShape.HideIcon();
        polyLayer.AddShape(tempShape);
        
        if (points.length >=1)
        {
            veMap.AttachEvent('onmouseout', mapDrawingMouseOut); 
            veMap.AttachEvent('onmouseover', mapDrawingMouseOver);   
        }
        if (points.length == 1)
            display('draw_clear');
        if (points.length == 3 && startPointSet != 1)
        {
            startPointSet = 1;
            startPin = new VEShape(VEShapeType.Pushpin,points[0]);
            startPin.SetCustomIcon("<img src='/Map/Images/mapcontrol/bttn-drawpolygon-end2.gif' onclick='Shape.EndDrawing()' />");
            startPin.ShowDetailOnMouseOver = false;
            polyLayer.AddShape(startPin);
        }
        if (points.length == 1)
            displayDrawingTip(2);
        if (points.length == 3)
            displayDrawingTip(3);
    }
    catch (err) {}
}
function mapDrawingMouseOut(e)
{
    var x = 0;
    var y = 0;
    var isPanning = false;
    var br = veMap.LatLongToPixel(veMap.GetMapView().BottomRightLatLong);
    if(e.mapX < 15 || e.mapX > br.x - 15)
    {
        if(e.mapX < 15)
        {
            x = -2;
        }
        else
        {
            x = 2;
        }
    }
    if(e.mapY < 15 || e.mapY > br.y - 15)
    {
        if(e.mapY < 15)
        {
            y = -2;
        }
        else
        {
            y = 2;
        }
    }
    if((x != 0 || y != 0))
    {
        veMap.StartContinuousPan(x,y);
        isPanning = true;
        return;
    }
    else
    {
        if(isPanning)
        {
            veMap.EndContinuousPan();
            isPanning = false;
        }
    }            

}
function mapDrawingMouseOver(e)
{
     veMap.EndContinuousPan();
}
function DetachDrawingEvents()
{
    veMap.DetachEvent('onclick', mapDrawingClick);
    veMap.DetachEvent('onmousemove', mapDrawingMouseMove);
    veMap.DetachEvent('onmouseout', mapDrawingMouseOut); 
    veMap.DetachEvent('onmouseover', mapDrawingMouseOver);   
    veMap.vemapcontrol.EnableGeoCommunity(false);
    hide('divDrawingTips');
    veMap.EndContinuousPan();
}
      
function GetClickLatLong(e)
{
    var x = e.mapX;
    var y = e.mapY;
    var pixel = new VEPixel(x, y);
    var latLong = veMap.PixelToLatLong(pixel);
    latLong.Latitude *= 10000;
    latLong.Latitude = Math.floor(latLong.Latitude)/10000;
    latLong.Longitude *= 10000;
    latLong.Longitude = Math.floor(latLong.Longitude)/10000;
    return latLong;
}
function displayDrawingTip(num)
{
    var tip = document.getElementById('drawingTip');
    if (tip)
    {
        switch (num)
        {
            case 1:
                tip.innerHTML = "<i>You are in Drawing mode.</i><br/>Click on the Starting Point of your Search Area to start drawing.";
                break;
            case 2:
                tip.innerHTML = "Click on the next point.<br/>Click 'Clear' to Start Over. You can click 'Cancel' button anytime to come out of drawing mode.";
                break;
            case 3:
                tip.innerHTML = "Now you can continue drawing<br/>OR <a href='javascript:;' onclick='Shape.EndDrawing()'>click here</a> to End Drawing.";
                break;
        }
    }
}

function CheckPolygonDrawn(type)
{
    var retVal;
    if (document.getElementById('draw_clear') && document.getElementById('draw_clear').style.display != 'none')
    {
        retVal = confirm("Entering a " + type + " will clear your drawn Polygon.\nClick 'OK' to clear your drawn Polygon and Zoom in to the entered " + type + ".");
        if (retVal)
            Shape.ClearDrawing();
        return retVal;
    } 
    return true;
}
Shape.DrawBoundaryByZip = function(val, noGo)
{
    if (!CheckPolygonDrawn('Zip'))
    {
        if (document.getElementById('ZipCode')) // clearout zip 
            document.getElementById('ZipCode').value = "";
        return;
    }
    if (val == '' || val == 'undefined')
    {
        if (document.getElementById('PolygonType').value == 'zip')
            DrawBoundary('');
        Search.submit(0);
        return;
    }   
    
    if (document.getElementById('selNeighborhood')) // clearout neighborhood selection
        document.getElementById('selNeighborhood').value = "";
        
    if (noGo != 1)
        map.GotoFirst(val);
        
    DrawBoundary('zip=' + val, noGo);
    document.getElementById('PolygonType').value = 'zip';
}


Shape.DrawBoundaryByNeighborhood = function(val, noGo, doPolySearch)
{
    if (!CheckPolygonDrawn('Neighborhood'))
    {
        if (document.getElementById('Neighborhood')) // clearout neighborhood 
            document.getElementById('Neighborhood').selectedIndex = 0;
        return;
    }
    document.getElementById('selNeighborhood').value = val;
    if (val == '' || val == 'undefined')
    {
        if (document.getElementById('PolygonType').value == 'neighborhood')
            DrawBoundary('');
        document.getElementById('PolyPoints').value = "";
        Search.submit(0);
        return;
    }      
    if (document.getElementById('City')) // clearout city 
        document.getElementById('City').value = "";
    if (document.getElementById('ZipCode')) // clearout zip 
        document.getElementById('ZipCode').value = "";

    DrawBoundary('nid=' + val, noGo, doPolySearch);
    document.getElementById('PolygonType').value = 'neighborhood';
}
Shape.DeletePolygons = function() {
    if (!CheckPolygonDrawn('Location')) {
        return false;
    }
    if (polyLayer2)
        polyLayer2.DeleteAllShapes();
    return true;

}
Shape.DrawBoundaryByCity = function(val, noGo)
{
    if (!CheckPolygonDrawn('City'))
    {
        if (document.getElementById('City')) // clearout  
            document.getElementById('City').value = "";
        return;
    }
    var city;
    var state;
    
    if (val == '' || val == 'undefined')
    {
        if (document.getElementById('PolygonType').value == 'city')
            DrawBoundary('');
            
        Search.submit(0);
        return;
    } 
    if (val.indexOf(",") > -1) // includes state
    {
        var arr = val.split(",");
        city = arr[0];
        state = arr[1].replace(' ', '');
    }
    else // pass in org state
    {
        state = document.getElementById('OrgState').value;
        city = val;
    }
    if (document.getElementById('selNeighborhood')) // clearout neighborhood selection
        document.getElementById('selNeighborhood').value = "";
        
    if (noGo != 1)
        map.GotoFirst(city + ',' + state);
    DrawBoundary('city=' + city + '&state=' + state, noGo);
    document.getElementById('PolygonType').value = 'city';
    //var objNeighborhood = document.getElementById('Neighborhood');
    //if (objNeighborhood)
    //    GetNeighborhoods('city=' + city + '&state=' + state, objNeighborhood);
       
}
var xmlhttp_b;
function DrawBoundary(qs, noGo, doPolySearch)
{//alert(qs);
    xmlhttp_b = null;
    if (qs == 'undefined' || qs == '')
    {
        if (polyLayer2)
            polyLayer2.DeleteAllShapes();
        
        document.getElementById('PolygonType').value == '';
        return;
    }    
    // prepare AJAX call
    var url = '/Map/AJAX/GetBoundary.aspx?cid=' + companyID + '&' + qs;
    xmlhttp_b = ajax.GetXmlHttpObject();
    xmlhttp_b.open('GET', url, true);
    xmlhttp_b.onreadystatechange = function() 
    {
        if (xmlhttp_b.readyState != 4 || xmlhttp_b.status != 200)  { return; }
        try 
        {
            var boundary = xmlhttp_b.responseText;
            DrawMultiPolygon(boundary, noGo, doPolySearch);
            
        } 
        catch(err) 
        {
            //alert("DrawBoundary: " + err.message);
        }
        
    }   
     xmlhttp_b.send(null);
 }
 
function DrawMultiPolygon(polyPoints, noGo, doPolySearch)
{   
    if (polyPoints == '' || polyPoints == 'undefined')
        return;
    var boundaryShape;
    var arrLatLong;
    var arrShape = new Array();
    var isWkt = 0; // if wkt change long lat to lat long
    try 
    {
        document.getElementById('PolyPoints').value = ""; // clear previous polypoints
        
        if (polyLayer2 == null) // create new
        {
            polyLayer2 = new VEShapeLayer();
            veMap.AddShapeLayer(polyLayer2);
        }
        else
            polyLayer2.DeleteAllShapes(); // cleanup
        
        if (polyPoints.indexOf("MULTIPOLYGON(((") > -1)
            isWkt = 1;
        polyPoints = polyPoints.replace("MULTIPOLYGON(((", "");
        polyPoints = polyPoints.replace(")))", "");
        
        var polygons = polyPoints.split("::");
        for(var j=0;j<polygons.length;j++)
        {
            var arrPoints = polygons[j].split(',');
            arrLatLong = new Array();

            if (isWkt == 1) {
                for (var i = 0; i < arrPoints.length; i++) {
                    point = arrPoints[i].split(" ");
                    arrLatLong[i] = new VELatLong(parseFloat(point[1]), parseFloat(point[0]));
                }

            }
            else {
                var ctr = 0;
                for (var i = 0; i < arrPoints.length / 2; i++) {
                    arrLatLong[i] = new VELatLong(parseFloat(arrPoints[ctr]), parseFloat(arrPoints[ctr + 1]));
                    ctr = ctr + 2;
                }
            }

            boundaryShape = new VEShape(VEShapeType.Polygon, arrLatLong);
            boundaryShape.SetFillColor(new VEColor(131, 185, 187, 0.1));
            boundaryShape.SetLineColor(new VEColor(186, 0, 255, 1.0)); 
            boundaryShape.SetLineWidth(2);
            boundaryShape.HideIcon();

            polyLayer2.AddShape(boundaryShape);  
            
            arrShape.push(boundaryShape);
        }
       if (doPolySearch == 1 && document.getElementById('PolyPoints'))
            document.getElementById('PolyPoints').value = arrLatLong;
       if (noGo != 1 && moveTo != 'undefined')
            veMap.SetMapView(arrShape); // position map over the drawn boundary. this will submit the search too
        else
            Search.submit(0); // if not moving, just submit the search
    }
    catch (err) 
    {
        //alert("DrawMultiPolygon: " + err.message);
        if (polyLayer2)
            polyLayer2.DeleteAllShapes();
    }
    
  
}

