﻿var map = null;
var isDrawingPolygon = false;
var isDrawingPolyline = false;
//var points = [];
var points = new Array();
var points1 = new Array();
var tempShapes = [];
var origCursor = null;
var polygon = null;
var drawing1 = false;
var stopdrawing = false;
var pointSelected = false;
var selectedIndex = -1;
var currentDragHandle = null;
var pinLayer = null;
var pointIndex = null;
var moving = false;
var k = 0;
var startingPoint = null;
var startingPoint1 = null;
var currentPoint = null;
var currentPoint1 = null;
var polylineMask = null;
var maskPoints = new Array(new VELatLong(0, 0), new VELatLong(0, 0));
var polyline = null;
var index = 0;
var results = null;
var pinID = 1;

function GetMapPoints() {
    return (polygon.GetPoints());
}

//function SetMapPoints(pnts) {
//    alert("Set:" + polygon.GetPoints());
//    polygon.SetPoints(pnts);
//}

function GetMap() {
    var points_array = new Array();
    var selected_pts = document.getElementById('map_points');
    map = new VEMap("MapDiv");

    //map.LoadMap();
    //map.SetZoomLevel(4);
    map.LoadMap();

    if (document.getElementById('map_city') != null) {
        polylineMask = new VEShape(VEShapeType.Polyline, maskPoints);
        polylineMask.HideIcon();
        polylineMask.SetLineColor(new VEColor(0, 0, 255, 0.5));
        map.AddShape(polylineMask);

        // Attach the event handlers to the mouse 
        map.AttachEvent("onmousedown", mouseDownHandler);
        map.AttachEvent("onmousemove", mouseMoveHandler);
        map.AttachEvent("onmouseup", mouseUpHandler);
        origCursor = document.getElementById('MapDiv').childNodes[0].style.cursor;
        zoom = 14;
        add = document.getElementById('map_address').value;
        city = document.getElementById('map_city').value;
        state = document.getElementById('map_state').value;
        zip = document.getElementById('map_zip').value;
        addline = add + ", " + city + ", " + state + ", " + zip;
        map.Find(null, addline, null, null, null, null, true, true, null, true, GetCoordinates);
    }
    else if (selected_pts != null && selected_pts.value != '') {
    polylineMask = new VEShape(VEShapeType.Polyline, maskPoints);
    polylineMask.HideIcon();
    polylineMask.SetLineColor(new VEColor(0, 0, 255, 0.5));
    map.AddShape(polylineMask);

    // Attach the event handlers to the mouse 
    map.AttachEvent("onmousedown", mouseDownHandler);
    map.AttachEvent("onmousemove", mouseMoveHandler);
    map.AttachEvent("onmouseup", mouseUpHandler);
    origCursor = document.getElementById('MapDiv').childNodes[0].style.cursor;
    zoom = 14;
    add = document.getElementById('map_address').value;
    city = document.getElementById('map_city').value;
    state = document.getElementById('map_state').value;
    zip = document.getElementById('map_zip').value;
    addline = add + ", " + city + ", " + state + ", " + zip;
    map.Find(null, addline, null, null, null, null, true, true, null, true, GetCoordinates);


/*
        var myvar = selected_pts.value;
        var p1 = new Array(
        new VELatLong(30.071470887901302, -95.44132232666016),
        new VELatLong(30.083651724486792, -95.29747009277345),
        new VELatLong(30.032838809330116, -95.28064727783205),
        new VELatLong(29.982297208594876, -95.40046691894534),
        new VELatLong(30.00667931286048, -95.4385757446289),
        new VELatLong(30.071470887901302, -95.44235229492188),
        new VELatLong(30.071470887901302, -95.44235229492188),
        new VELatLong(30.071470887901302, -95.44132232666016)
        );


        polylineMask = new VEShape(VEShapeType.Polyline, maskPoints);
        polylineMask.HideIcon();
        polylineMask.SetLineColor(new VEColor(0, 0, 255, 0.5));
        map.AddShape(polylineMask);

        // Attach the event handlers to the mouse 
        map.AttachEvent("onmousedown", mouseDownHandler);
        map.AttachEvent("onmousemove", mouseMoveHandler);
        map.AttachEvent("onmouseup", mouseUpHandler);
        origCursor = document.getElementById('MapDiv').childNodes[0].style.cursor;
        //zoom = 14;

     

        var color = new VEColor(255, 0, 0, 1);
        var width = 5;
        polyline = new VEShape(VEShapeType.Polyline, p1, color, width);
        polyline.HideIcon();
        map.AddShape(polyline);
        //maskPoints[1] = currentLatLon;

        pinLayer = new VEShapeLayer();
        map.AddShapeLayer(pinLayer);

        map.SetCenterAndZoom(p1[0], 9);
        keyPressHandler(null);
        */
        //Draw();
        //toggleEdit();
        
        /*
        var color = new VEColor(0, 0, 255, 0.5);
        var width = 2;
        var id = '';

        var poly = new VEPolyline(id, p1, color, width);
        map.AddPolyline(poly);
        map.SetMapView(p1);
        Draw();
        toggleEdit();
        */
        /*
        add = document.getElementById('map_address').value;
        city = document.getElementById('map_city').value;
        state = document.getElementById('map_state').value;
        zip = document.getElementById('map_zip').value;
        addline = add + ", " + city + ", " + state + ", " + zip;
        map.Find(null, addline, null, null, null, null, true, true, null, true, GetCoordinates);
        */
    }
}

function GetCoordinates(layer, resultsArray, places, hasMore, veErrorMessage) {
    findPlaceResults = places[0].LatLong;
    var myShape = new VEShape(VEShapeType.Pushpin, findPlaceResults);
    //myShape.SetDescription(findPlaceResults.toString());
    map.AddShape(myShape);
    map.SetZoomLevel(12);
}
function toggleEdit() {

    try {
        if (!pinLayer.GetVisibility()) {
            if (document.getElementById('HdnSelectMap') != null)
                document.getElementById('HdnSelectMap').value = '1';

            pinLayer.Show();
            drawing1 = true;
            document.getElementById("cmdEdit").value = ' Edit Map ';
            document.getElementById('ModeIndicator').innerHTML = 'Enabled';


        }
        else {
            if (document.getElementById('HdnSelectMap') != null)
                document.getElementById('HdnSelectMap').value = '1';

            pinLayer.Hide();
            drawing1 = true;
            keyPressHandler();
            document.getElementById("cmdEdit").value = ' Edit Map ';
            document.getElementById('ModeIndicator').innerHTML = 'Disabled';
        }
    }
    catch (ex) {
        //alert(' Please select an area in the map ');
        if (document.getElementById('HdnSelectMap') != null)
            document.getElementById('HdnSelectMap').value = '1';
    }

}

//////////////////////////////////////////////////
function mouseDownHandler(e) {
    var IsValid2SelectMap = false;

    if (document.getElementById('HdnSelectMap') != null && document.getElementById('HdnSelectMap').value == '1') {
        IsValid2SelectMap = true;
    }

    if (IsValid2SelectMap) {
        if (document.getElementById('DivErrorMsg') != null)
            document.getElementById('DivErrorMsg').innerHTML = '';


        SetCursor(true);
        isDrawingPolygon = true;
        start = true;

        // Start drawing a polygon
        if (isDrawingPolygon && !stopdrawing) {
            // Retrieve the location where we clicked.
            var loc = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
            currentLatLon = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
            points1.push(currentLatLon);
            maskPoints[0] = currentLatLon;
            if (e.leftMouseButton && !e.rightMouseButton) {

                // Left click.
                points.push(loc);
                points1.push(loc);
                maskPoints[0] = currentLatLon;
                // We add a temporary shape to the map, just as a placeholder.
                var shape = new VEShape(VEShapeType.Pushpin, loc);
                shape.SetCustomIcon('images/HomeIcon.gif');
                shape.HideIcon();
                map.AddShape(shape);
                maskPoints[1] = currentLatLon;
                tempShapes.push(shape);

                if (points1.length > 1) {
                    if (!polyline) {
                        var color = new VEColor(255, 0, 0, 1);
                        var width = 5;
                        polyline = new VEShape(VEShapeType.Polyline, points1, color, width);
                        polyline.HideIcon();
                        map.AddShape(polyline);
                        maskPoints[1] = currentLatLon;

                    } else {
                        polyline.SetPoints(points1);
                    }
                    if (e.elementID) {
                        currentDragHandle = map.GetShapeByID(e.elementID);
                        var handleLocation = currentDragHandle.GetPoints();
                        for (i = 0; i <= (points.length - 1); i++) {
                            var pointLocation = points[i].toString();
                            if (handleLocation == pointLocation) {
                                closePolygon(e, loc);
                            }
                        }
                    }

                }

                //var origin = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
                //	for (i = 0; i <= (points.length - 1); i++){
                //		if(i == 0){
                //		startingPoint = points[i].toString().substring(0,5);
                //		}
                //		currentPoint = origin.toString().substring(0,5);
                //		if(i >1){
                //		if (startingPoint == currentPoint )
                //		{
                //		closePolygon(e,loc);
                //		}
                //		}
                //	}

                // This is to prevent further click processing.
                return false;
            }
            else {
                //Nothing to do here.
                return true;
            }

        }
        else if (e.elementID && drawing1) {

            currentDragHandle = map.GetShapeByID(e.elementID);
            if (currentDragHandle.GetType() == VEShapeType.Pushpin) {
                moving = true;
                polylineMask.Show();
                map.vemapcontrol.EnableGeoCommunity(true);
                document.getElementById("MapDiv").style.cursor = 'crosshair';

                //Determine point index
                var handleLocation = currentDragHandle.GetPoints();

                for (i = 0; i <= (points.length - 1); i++) {
                    var pointLocation = points[i].toString();
                    if (handleLocation == pointLocation) {
                        pointIndex = i;
                        break;
                    }
                }
            }
        }
    }
}

function closePolygon(e, loc) {

    if (polyline) {
        map.DeleteShape(polyline);
        map.DeleteShape(polylineMask);
        polyline = null;
        points1.length = 0;
    }

    points.push(loc);
    points1.push(loc);
    // Time to draw the shape.
    Draw();

    //Get Details from DataBase
    keyPressHandler(e)

    if (!polyline) {
        pinLayer = new VEShapeLayer();
        map.AddShapeLayer(pinLayer);
        for (i = 0; i <= (points.length - 1); i++) {
            var dragHandle = new VEShape(VEShapeType.Pushpin, points[i]);
            dragHandle.SetCustomIcon('images/UD_GoButtonBg_over.gif');

            pinLayer.AddShape(dragHandle);
        }
        pinLayer.Hide();
    }

}


//onmousemove handler
function mouseMoveHandler(e) {

    if (isDrawingPolygon && !stopdrawing) {
        var loc = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
        if (points1.length > 0) { polylineMask.Show() };
        maskPoints[1] = loc
        polylineMask.SetPoints(maskPoints);
    }
    if (moving) {
        var loc = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
        currentDragHandle.SetPoints(loc);
        points[pointIndex] = loc;
        polygon.SetPoints(points);
        //alert(points);

    }

}

function mouseUpHandler(e) {

    if (moving) {
        moving = false;
        polylineMask.Hide();
        map.vemapcontrol.EnableGeoCommunity(false);
        document.getElementById("MapDiv").style.cursor = '';
        //polyline.SetPoints(points1);
        polygon.SetPoints(points);
        keyPressHandler(e)
    }

}




//////////////////////////////////////////////////
function Draw() {

    // Time to remove the placeholder shapes we used.
    for (var i = 0; i < tempShapes.length; i++) {
        map.DeleteShape(tempShapes[i]);
    }
    
    if (isDrawingPolygon) {
        if (points.length < 3) {
            alert("At least 3 points are necessary to draw a polygon! :)");
        }
        else {

            polygon = new VEShape(VEShapeType.Polygon, points);
            polygon.HideIcon();
            map.AddShape(polygon);
        }
    }

    else {
        // How did you get here?
    }

    // Reset some variables.
    isDrawingPolygon = false;
    //points = [];
    SetCursor(false);
}



//////////////////////////////////////////////////
function SetCursor(isDrawing) {
    document.getElementById('MapDiv').childNodes[0].style.cursor = isDrawing ? "crosshair" : origCursor;
}

function keyPressHandler(e) {
    points1.length = 0;
    polylineMask.Hide();
    stopdrawing = true;
    var pts = points;
    //prompt("",pts);

    pts = pts.toString().replace(/, -/g, ' -');
    var map_points = pts.toString();

    var i;
    var j = 0;
    var start;
    var last;
    var firstString;
    var lastString;
    for (i = 0; i < pts.length; i++) {
        if (pts.charAt(i) == ',') {
            j++;
            last = i;
            if (j == 1) {
                start = i;
                firstString = pts.substring(0, i);
            }
        }
    }

    pts = firstString + pts.substring(start, last + 1) + firstString;

    try {
        pts = pts.toString().replace(/,/g, '|');

        //EnableProgressBar();

        //if (document.getElementById('cmdSubmit') != null)
        // document.getElementById('cmdSubmit').style.display = 'none';

        //if (document.getElementById('cmdRefresh') != null)
        //  document.getElementById('cmdRefresh').disabled = true

        //if (document.getElementById('cmdEdit') != null)
        //document.getElementById('cmdEdit').disabled = true
        var obj;
        obj = document.getElementById('DivErrorMsg');
        obj = document.getElementById('cmdEdit');
        obj = document.getElementById('need_map');
        obj = document.getElementById('pts_box');
        //obj = $get('<%= pts_box.ClientID %>');


        if (document.getElementById('DivErrorMsg') != null) {
            document.getElementById('DivErrorMsg').innerHTML = '';
        }

        if (document.getElementById('cmdEdit') != null && document.getElementById('cmdEdit').value != 'Click to end edit') {
            document.getElementById('cmdEdit').value = ' Edit Map ';
            document.getElementById('statusbar').style.display = "block";
        }

        //SendQueryForMAP(pts, 'result', 'MapView', 'GetZipCodesfromMap', 'AjaxServer.aspx');
        //getdata(pts);

        //document.getElementById('need_map').style.display = 'none';
        //document.getElementById('has_map').style.display = 'block';
        var pb = document.getElementById('pts_box');
        pb.value = pts;
        pb = document.getElementById('map_points');
        if (pb != null) {
            pb.value = map_points;
        }
        //document.getElementById('ctl00$content_right_form$AccordionPane4_content$pts_box').value = pts;
        //alert(pts);

    }
    catch (e) {
        alert("Please draw a polygon without overlaping" + e);
    }
    
    function SendValueToParent()

    {
        var myVal = document.getElementById('pts_box').value;
        opener.document.getElementById('pts_box').value = myVal;
        window.close();
        return false;
    }

}

   