﻿function ToolbarControl(map, x, y) {
    this._drawingCircle = false;
    this._drawingRect = false;
    this._map = map;
    this._e = new Sys.EventHandlerList();
    this._poly = null;
    if (x) this._posX = x;
    else this._posX = 100;
    if (y) this._posY = y;
    else this._posY = 7;
}

ToolbarControl.prototype = new GControl();

ToolbarControl.prototype.initialize = function(map) {
    this._map = map;
    var container = document.createElement("div");
    container.className = 'toolbar';

    this.rect = document.createElement("div");
    this.rect.className = 'button rectangle';
    var that = this;
    GEvent.addDomListener(this.rect, "click", function() {
        that.toggleDrawingRectangle();
    });

    this.circle = document.createElement("div");
    this.circle.className = 'button circle';
    container.appendChild(this.circle);
    GEvent.addDomListener(this.circle, "click", function() {
        that.toggleDrawingCircle();
    });
    map.getContainer().appendChild(container);
    return container;
}

ToolbarControl.prototype.getFigure = function() {
    if (this.cFirst == null || this.cSecond == null) {
        return null;
    }
    var ret = { valid: true,
        first: new GLatLng(this.cFirst.lat(), this.cFirst.lng()),
        second: new GLatLng(this.cSecond.lat(), this.cSecond.lng())
    };
    if (this._drawingCircle) {
        ret.figure = 'circle';
        return ret;
    } else if (this._drawingRect) {
        ret.figure = 'rect';
        return ret;
    }
    return null;
}

ToolbarControl.prototype.toggleDrawingCircle = function() {
    if (this._drawingCircle)
        this.stopDrawingCircle();
    else
        this.startDrawingCircle();
}

ToolbarControl.prototype.startDrawingCircle = function() {
    if (this._drawingCircle)
        return;
    this._drawingRect = false;
    this._drawingCircle = true;
    this._fixCss(this._drawingRect, this._drawingCircle);
    this.startDrawing();
}

ToolbarControl.prototype.FixDrawingCircle = function() {
    this._drawingRect = false;
    this._drawingCircle = true;
    this._fixCss(this._drawingRect, this._drawingCircle);
}

ToolbarControl.prototype.stopDrawingCircle = function() {
    if (!this._drawingCircle)
        return;
    this._drawingRect = false;
    this._drawingCircle = false;
    for (i = 0; i < 2 - this.line.getVertexCount(); i++)
        this.line.insertVertex(i, new GLatLng(0, 0));
    for (i = 0; i < 2; i++)
        this.line.deleteVertex(i);
    this.line.hide();
    this.line.disableEditing();
    this._fixCss(this._drawingRect, this._drawingCircle);
    this._clearFigures();
    this._onDragEnd();

}

ToolbarControl.prototype.toggleDrawingRectangle = function() {
    if (this._drawingRect)
        this.stopDrawingRectangle();
    else
        this.startDrawingRectangle();
}

ToolbarControl.prototype.startDrawingRectangle = function() {
    if (this._drawingRect)
        return;
    this._drawingRect = true;
    this._drawingCircle = false;
    this._fixCss(this._drawingRect, this._drawingCircle);
    this.startDrawing();
}

ToolbarControl.prototype.stopDrawingRectangle = function() {
    if (!this._drawingRect)
        return;
    this._drawingRect = false;
    this._drawingCircle = false;
    this._fixCss(this._drawingRect, this._drawingCircle);
    
}

ToolbarControl.prototype.startDrawing = function() {
    this._clearFigures();
    var poly = new GPolyline([], "#01467b", 2, 0.8);
    this.line = poly;

    this._map.addOverlay(poly);
    poly.enableDrawing({ maxVertices: 2 });
    poly.enableEditing({ onEvent: "mouseover" });
    poly.disableEditing({ onEvent: "mouseout" });
    var that = this;
    this.cNodeCount = 0;
    this.cCoord = null;
    this.cDrawFigure = false;
    var lineUpdatedH = GEvent.addListener(poly, "lineupdated", function() {
        if (that.cNodeCount == 0) {
            that.cCoord = poly.getVertex(0);
            that.cDrawFigure = true;
        }
        that.cNodeCount++;
    });
    var mouseMoveH = GEvent.addListener(this._map, "mousemove", function(coord) {
        if (that.cNodeCount > 0 && that.cDrawFigure) {
            that._drawLate(that.cCoord, coord);
        }
    });
    var endLineH = GEvent.addListener(poly, "endline", function() {
        if (endLineH == null)
            return;
        that.cDrawFigure = false;
        that._raiseFigureCompleted();
        GEvent.removeListener(mouseMoveH);
        GEvent.removeListener(lineUpdatedH);
        GEvent.removeListener(endLineH);

        that._drawLate(poly.getVertex(0), poly.getVertex(1));
        GEvent.bind(poly, "drag", that, that._onDrag);
        GEvent.bind(poly, "dragend", that, that._onDragEnd);
        endLineH = null;
    });
}



ToolbarControl.prototype._drawPoly = function(first, second, func) {
    this._drawingRect = false;
    this._drawingCircle = true;

    var poly = new GPolyline([], "#01467b", 2, 0.8);
    this.line = poly;

    this._map.addOverlay(poly);
    poly.enableDrawing({ maxVertices: 2 });
    poly.enableEditing({ onEvent: "mouseover" });
    poly.disableEditing({ onEvent: "mouseout" });
    var that = this;
    this.cNodeCount = 1;
    this.cDrawFigure = false;

    poly.insertVertex(0, first);
    poly.insertVertex(1, second);
    that.cCoord = first;
    this._poly = poly;
    if (!this.cTimeout)
        this.cTimeout = setTimeout(Function.createDelegate(this, this._drawAfterPolyInsert), 1000);
}
ToolbarControl.prototype._drawAfterPolyInsert = function() {
    this.cTimeout = null;
    var that = this;
    that._drawLate(this._poly.getVertex(0), this._poly.getVertex(1));
    GEvent.bind(this._poly, "drag", that, that._onDrag);
    GEvent.bind(this._poly, "dragend", that, that._onDragEnd);
    endLineH = null;
}
ToolbarControl.prototype._onDrag = function(el) {
    var first = el.line.getVertex(0);
    var second = el.line.getVertex(1);
    if (el.index == 0 || el.index == 1) {
        this._drawLate(first, second);
    }
}

ToolbarControl.prototype._onDragEnd = function(el) {
    this._raiseFigureChanged();
}


ToolbarControl.prototype._drawLate = function(center, edge) {

    this.cFirst = center;
    this.cSecond = edge;
    this._raiseSearchReady();
    if (!this.cTimeout)
        this.cTimeout = setTimeout(Function.createDelegate(this, this._drawAfter), 100);
}

ToolbarControl.prototype.add_searchReady = function(handler) {
    this._e.addHandler('searchReady', handler);
}

ToolbarControl.prototype._raiseSearchReady = function() {
    var handler = this._e.getHandler('searchReady');
    if (handler) {
        handler(this);
    }
}
ToolbarControl.prototype.remove_searchReady = function(handler) {
    var handler = this._e.getHandler('searchReady');
    if (handler)
        this._e.removeHandler('searchReady', handler);
}


ToolbarControl.prototype._drawAfter = function() {
this.cTimeout = null;
    if (this._drawingCircle)
        this._drawCircle(this.cFirst, this.cSecond);
    else if (this._drawingRect)
        this._drawRect(this.cFirst, this.cSecond);
}

ToolbarControl.prototype._clearFigures = function() {
    if (this.line != null)
        this._map.removeOverlay(this.line);
    if (this._lastFig != null)
        this._map.removeOverlay(this._lastFig);
    this.cFirst = null;
    this.cSecond = null;
    this._raiseFigureRemoved();
}

ToolbarControl.prototype._drawCircle = function(center, edge, nodes, liColor, liWidth, liOpa, fillColor, fillOpa) {
       fillColor = "#005291";
       liColor = "#01467b";
       liOpa = 0.45;
       liWidth = liWidth || 2;

    var circlePoints = Array();

    with (Math) {
        var d = center.distanceFrom(edge) / 1000 / 6378.8;
        var lat1 = (PI / 180) * center.lat(); // radians
        var lng1 = (PI / 180) * center.lng(); // radians
        for (var a = 0; a < 361; a+=6) {
            var tc = (PI / 180) * a;
            var y = asin(sin(lat1) * cos(d) + cos(lat1) * sin(d) * cos(tc));
            var dlng = atan2(sin(tc) * sin(d) * cos(lat1), cos(d) - sin(lat1) * sin(y));
            var x = ((lng1 - dlng + PI) % (2 * PI)) - PI; // MOD function
            circlePoints.push(new GLatLng(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI))));
        }
        if (this._lastFig != null)
            this._map.removeOverlay(this._lastFig);
        if (d < 1.5678565720686044) {
            poly = new GPolygon(circlePoints, liColor, liWidth, liOpa, fillColor, fillOpa);
        }
        else {
            poly = new GPolygon(circlePoints, liColor, 2, 1);
        }
    }
    this._lastFig = poly;
    this._map.addOverlay(poly);
}

ToolbarControl.prototype._drawRect = function(topLeft, bottomRight, liColor, liWidth, liOpa, fillColor, fillOpa) {

    var points = [];
    var pint = new GLatLng(topLeft.lat(), topLeft.lng());
    points.push(pint);
    pint = new GLatLng(topLeft.lat(), bottomRight.lng());
    points.push(pint);
    pint = new GLatLng(bottomRight.lat(), bottomRight.lng());
    points.push(pint);
    pint = new GLatLng(bottomRight.lat(), topLeft.lng());
    points.push(pint);

    points.push(points[0]); // Closes the circle, thanks Martin
    fillColor = "#363636";
    liColor = "#2c2c2c";
    liOpa = 0.45;
    liWidth = liWidth || 2;
    var poly = new GPolygon(points, liColor, liWidth, liOpa, fillColor, fillOpa);
    if (this._lastFig != null)
        this._map.removeOverlay(this._lastFig);
    this._lastFig = poly;
    this._map.addOverlay(poly);
}

ToolbarControl.prototype._fixCss = function(rect, circle) {
    if (rect && circle) {
        rect = false;
        circle = false;
    }
    if (circle) {
        this.circle.className = 'button circle_h';
    } else {
        this.circle.className = 'button circle';
    }
    
    if (rect) {
        this.rect.className = 'button rectangle_h';
    } else {
        this.rect.className = 'button rectangle';
    }
}

ToolbarControl.prototype.add_figureCompleted = function(handler) {
        this._e.addHandler('figureCompleted', handler);
}

ToolbarControl.prototype.remove_figureCompleted = function(handler) {
        this._e.removeHandler('figureCompleted', handler);
}

ToolbarControl.prototype._raiseFigureCompleted = function() {
    var handler = this._e.getHandler('figureCompleted');
    if (handler) {
        handler(this);
    }
}

ToolbarControl.prototype.add_figureChanged = function(handler) {
    this._e.addHandler('figureChanged', handler);
}

ToolbarControl.prototype.remove_figureChanged = function(handler) {
    this._e.removeHandler('figureChanged', handler);
}

ToolbarControl.prototype._raiseFigureChanged = function() {
    var handler = this._e.getHandler('figureChanged');
    if (handler) {
        handler(this);
    }
}

ToolbarControl.prototype.add_figureRemoved = function(handler) {
    this._e.addHandler('figureRemoved', handler);
}

ToolbarControl.prototype.remove_figureRemoved = function(handler) {
    this._e.removeHandler('figureRemoved', handler);
}

ToolbarControl.prototype._raiseFigureRemoved = function() {
    var handler = this._e.getHandler('figureRemoved');
    if (handler) {
        handler(this);
    }
}

ToolbarControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(this._posX, this._posY));
}


