﻿/// <reference name="MicrosoftAjax.js" />

var map = null;
Sys.Application.add_load(onLoad);
Sys.Application.add_unload(onUnload);

function SizeContentArea() {
    var elementBounds = Sys.UI.DomElement.getBounds($get('mainbody'));
    var leftNav = Sys.UI.DomElement.getBounds($get('controls'));
    var mapWidth = elementBounds.width - leftNav.width - 10;
    var mapHeight = mapWidth * 0.6;

    $get('content').style.width = mapWidth + 'px';
    $get('myMap').style.height = Math.min(mapHeight, 600) + 'px';
}

function onLoad() {
    $get("MoveLocation").focus();
    $addHandler($get("MoveLocation"), "keypress", clickButton);
    $addHandler(window, 'resize', SizeContentArea);
    SizeContentArea();

    map = new VEMap('myMap');
    map.LoadMap(new VELatLong(52, -0.8), 7, 'h', false);
}

function onUnload() {
    $removeHandler($get("MoveLocation"), "keypress", clickButton);
    $removeHandler(window, 'resize', SizeContentArea);
}

var shape = null;
var currentShapePoints = new Array();
var currentShapeType = null;
var shapeCollection = new Array;

function drawShape(shapetype) {
    currentShapeType = shapetype;
    currentShapePoints.length = 0;
    attachEventHandlers();
}

function attachEventHandlers() {
    map.AttachEvent("onclick", recordPoint);
    $get("myMap").childNodes[0].style.cursor = "crosshair";
}

function detachEventHandlers() {
    $get("myMap").childNodes[0].style.cursor = "";
    map.DetachEvent("onclick", recordPoint);
}

function startOver() {
    map.DeleteAllShapes();
    shapeCollection.length = 0;
    $get('SqlOutput').innerText = 'Generated SQL statements will appear here.';
    EnableDisableControls(false);
    $get('GenSql').disabled = true;
}

function recordPoint(e) {
    var pix = new VEPixel(e.mapX, e.mapY);
    var pos = map.PixelToLatLong(pix);

    currentShapePoints[currentShapePoints.length] = pos;

    switch (currentShapeType) {
        case VEShapeType.Pushpin:
            shape = new VEShape(VEShapeType.Pushpin, currentShapePoints);
            map.AddShape(shape);
            break;
        case VEShapeType.Polyline:
        case VEShapeType.Polygon:
            if (currentShapePoints.length == 2) {
                shape = new VEShape(VEShapeType.Polyline, currentShapePoints);
                map.AddShape(shape);
            }
            if (currentShapePoints.length > 2) {
                map.DeleteShape(shape);
                shape = new VEShape(currentShapeType, currentShapePoints);
                map.AddShape(shape);
            }
            break;
        default:
            detachEventHandlers();
            throw ("Unexpected shape type");
    }

    if (e.rightMouseButton == true || currentShapeType == 'Point') {
        detachEventHandlers();
        EnableDisableControls(true);
    }
}

function setfeaturename(FeatureName) {
    var illegalChars = /\W/;
    if (illegalChars.test(FeatureName) || FeatureName.length == 0) {
        alert('Please enter a valid name for the feature you\'ve just added. Valid names can contain only letters, numbers and underscore characters.');
        $get('FeatureName').focus();
    }
    else {
        var newShape = new Object();
        newShape.ID = shape.GetID();
        newShape.Name = FeatureName;
        shapeCollection[shapeCollection.length] = newShape;

        EnableDisableControls(false);
    }
}

function EnableDisableControls(WaitingNameEntry) {
    $get('DrawPoint').disabled = WaitingNameEntry;
    $get('DrawLine').disabled = WaitingNameEntry;
    $get('DrawPolygon').disabled = WaitingNameEntry;
    $get('GenSql').disabled = WaitingNameEntry;

    $get('SubmitFeatureName').disabled = !WaitingNameEntry;

    if (WaitingNameEntry == true) {
        $get('FeatureName').value = "";
        $get('FeatureName').focus();
    }
}

function genSql(FeatureNameColumnName, FeatureGeographyColumnName, TableName) {
    var illegalChars = /\W/;
    if (illegalChars.test(FeatureNameColumnName) ||
        FeatureNameColumnName.length == 0 ||
        illegalChars.test(FeatureGeographyColumnName) ||
        FeatureGeographyColumnName.length == 0 ||
        illegalChars.test(TableName) ||
        TableName.length == 0) {
        alert('Please enter valid names for columns and table. Valid names can contain only letters, numbers and underscore characters.');
        $get('FeatureNameColumnName').focus();
    }
    else {
        generateSql(FeatureNameColumnName, FeatureGeographyColumnName, TableName);
    }
}

function generateSql(FeatureNameColumnName, FeatureGeographyColumnName, TableName) {
    var shapeName;
    var currentShape;
    var points;
    var sb = new Sys.StringBuilder();
    var pointsString = new Sys.StringBuilder();
    var wktShapeType;

    for (var i = 0; i < shapeCollection.length; i++) {
        shapeName = shapeCollection[i].Name;
        currentShape = map.GetShapeByID(shapeCollection[i].ID);
        points = currentShape.GetPoints();
        pointsString.clear();

        for (var j = 0; j < points.length; j++) {
            pointsString.append(((j > 0) ? ", " : "") + points[j].Longitude + " " + points[j].Latitude);
        } 

        switch (currentShape.GetType()) {
            case VEShapeType.Pushpin:
                wktShapeType = 'POINT';
                break;
            case VEShapeType.Polyline:
                wktShapeType = 'LINESTRING';
                break;
            case VEShapeType.Polygon:
                wktShapeType = 'POLYGON';
                break;
            default:
                throw ("Unexpected shape type");
        }

        sb.appendLine("INSERT into " + TableName + " (" +
                FeatureNameColumnName + ", " +
                FeatureGeographyColumnName + ") VALUES ('" +
                shapeName + "', geography::STGeomFromText('" + wktShapeType +
                (wktShapeType == 'POLYGON' ? "((" : "(") +
                pointsString +
                (wktShapeType == 'POLYGON' ? "))" : ")") +
                "', 4326))");

        sb.appendLine();
    }

    $get('SqlOutput').innerText = sb.toString();
}

function moveMapToLocation(Location) {

    map.Find(null, Location,
             null, null, null, null, null, null,
             false, true,

    function() {
        var pPin = new VEShape(VEShapeType.Pushpin, map.GetCenter());
        pPin.SetTitle(Location);
        map.AddShape(pPin);
    });
}

function clickButton(args) {
    if (args.charCode == 13 && $get("MoveLocation").value.length > 0) {
        $get("GoFind").click();
        return false;
    }
}