﻿function showNode(index_) {
    map.setCenter(poly.getVertex(index_));
    showBlowup();
}

GLatLngBounds.prototype.drawBox = function(opt_options) {
    var opts = opt_options || {};
    var northEast = this.getNorthEast();
    var southWest = this.getSouthWest();
    var topLat = northEast.lat();
    var rightLng = northEast.lng();
    var botLat = southWest.lat();
    var leftLng = southWest.lng();
    var pnts = [];
    pnts.push(southWest);
    pnts.push(new GLatLng(topLat, leftLng));
    pnts.push(northEast);
    pnts.push(new GLatLng(botLat, rightLng));
    pnts.push(southWest);
    var fillColor = opts.fillColor || opts.liColor || "#0055ff";
    var liWidth = opts.liWidth || 2;
    if (opts.polygon) {
        var boxPoly = new GPolygon(pnts, opts.liColor, liWidth, opts.liOpa, fillColor, opts.fillOpa);
    } else {
        var boxPoly = new GPolyline(pnts, opts.liColor, liWidth, opts.liOpa);
    }
    return boxPoly;
}


var poly = null;
var updateListener;
function rectPoly() {
    map.clearOverlays();
    updateListener = null;
    map.zoomIn();
    poly = map.getBounds().drawBox();
    map.addOverlay(poly);
    map.zoomOut();
    poly.enableEditing();
    setListener(poly);
    listPoly();
}


function drawPoly() {
    map.clearOverlays();
    updateListener = null;

    poly = new GPolyline([], "blue", 2);
    map.addOverlay(poly);
    poly.enableDrawing();
    setListener(poly);
}



function drawRoute() {
    map.clearOverlays();
    updateListener = null;
    poly = gdir.getPolyline();
    var vert = poly.getVertexCount();
    var permission = true;
    if (vert > 100) permission = confirm(vert + " points are not editable but I can draw it.");
    if (!permission) return;
    if (vert > 1000) permission = confirm(vert + " points is much. Are you really serious?");
    if (!permission) return;
    if (vert > 10000) permission = confirm(vert + " points. This is your last change. Proceed?");
    if (permission) {
        map.addOverlay(poly);
        setListener(poly);
        map.fit(poly.getBounds(), true);
        listPoly();
    }
}

function drawPunto() {

    var bounds = map.getBounds();
    var span = bounds.toSpan();
    var southWest = bounds.getSouthWest();
    map.clearOverlays();
    markers.length = 0;
    var str = $("memo").value
    var lat = Mid(str, 1, InStr(str, ",") - 1)
    var lon = Mid(str, InStr(str, ",") + 1, str.length - InStr(str, ","))
    var point = new GLatLng(lat, lon);
    var marker = (new GMarker(point, { draggable: true, autoPan: false }));

    map.addOverlay(marker);
    //GEvent.addListener(marker, 'dragend', function(){show();});
    markers.push(marker);
    GEvent.addListener(marker, 'dragend', function(markerPoint) {
        if (!map.getBounds().containsLatLng(markerPoint)) {
            map.removeOverlay(this);
            map.removeOverlay(this.poly);
        } else {
            //geocode(this.getLatLng(), this);
        }
        $("memo").value = marker.getLatLng();
    });
    document.getElementById('puntoLink').style.visibility = "hidden";

}

function drawFromText() {
    map.clearOverlays();
    updateListener = null;
    var polyPoints = $("memo").value.parseCsv();
    poly = new GPolyline(polyPoints, "blue", 2);
    map.addOverlay(poly);
    var bounds = poly.getBounds();
    if (bounds) map.fit(bounds, true);
    setListener(poly);

}

function setListener(obj) {
    updateListener = GEvent.addListener(obj, "lineupdated", function() { if ($("update").checked) listPoly(); });
    GEvent.addListener(map, "dblclick", function() { listPoly(); });
}
function listPoly() {
    clearSelector();
    var rows = [];
    $("memo").value = "";
    if (poly) {
        var len = poly.getVertexCount() || 0;
        for (var i = 0; i < len; i++) {
            var point = poly.getVertex(i);
            rows.push(point.lng().toFixed(6) + ", " + point.lat().toFixed(6));
            addOption(i);
        }
        $("memo").value = rows.join('\n');
    }
    //$("vertices").innerHTML = len + " vertices . ";
}

var geocoder = new GClientGeocoder();
function showAddress(address, id) {
    geocoder.getLatLng(address, function(point) {
        if (!point) {
            $(id).style.color = "#ff0000";
        } else {
            map.setCenter(point);
            rectPoly();
            $(id).style.color = "#000000";
            $("memo").value = "";
        }
    })
}

GMap2.prototype.fit = function(bounds, save) {
    if (!save) {
        this.setZoom(map.getBoundsZoomLevel(bounds));
        this.panTo(bounds.getCenter());
    } else {
        this.setCenter(bounds.getCenter(), this.getBoundsZoomLevel(bounds));
        this.savePosition();
    }
}



String.prototype.parseCsv = function(opt_options) {
    var results = [];
    var opts = opt_options || {};
    var iLat = opts.lat || 1;
    var iLng = opts.lng || 0;
    var lines = this.split("\n");
    for (var i = 0; i < lines.length; i++) {
        var blocks = lines[i].split('"');
        //finding commas inside quotes. Replace them with '::::'
        for (var j = 0; j < blocks.length; j++) {
            if (j % 2) {
                blocks[j] = blocks[j].replace(/,/g, '::::');
            }
        }  //@author Esa 2008, keep this note.
        lines[i] = blocks.join("");
        var lineArray = lines[i].split(",");
        var lat = lineArray[iLat] * 1;
        var lng = lineArray[iLng] * 1;
        var point = new GLatLng(lat, lng);
        //after splitting by commas, we put hidden ones back
        for (var cell in lineArray) {
            lineArray[cell] = lineArray[cell].replace(/::::/g, ',');
        } //corrupted line step-over
        if (!isNaN(lat + lng)) {
            point.textArray = lineArray;
            results.push(point);
        }
    }
    return results;
}


function createMarker() {
    marker = new GMarker(map.getCenter(), { draggable: true, autoPan: false });
    map.addOverlay(marker);

    GEvent.addListener(marker, 'dragend', function(markerPoint) {
        if (!map.getBounds().containsLatLng(markerPoint)) {
            map.removeOverlay(this);
            map.removeOverlay(this.poly);
        } else {
            //geocode(this.getLatLng(), this);
        }
        $("memo").value = marker.getLatLng();
    });
    return marker
}

function follow(imageInd) {
    document.getElementById('puntoLink').style.visibility = "hidden";
    var dog = true;
    var noMore = false;

    var mouseMove = GEvent.addListener(map, 'mousemove', function(cursorPoint) {
        if (!noMore) {
            marker = createMarker();
            noMore = true;
        }
        if (dog) {
            marker.setLatLng(cursorPoint);
        }
    });
    var mapClick = GEvent.addListener(map, 'click', function() {
        dog = false;
        $("memo").value = marker.getLatLng();
        //geocode(marker.getLatLng(), marker);
        // 'mousemove' event listener is deleted for saving resources
        GEvent.removeListener(mouseMove);
        GEvent.removeListener(mapClick);
    });
}



function Mid(String, Start, Length) {
    if (String == null)
        return (false);

    if (Start > String.length)
        return '';

    if (Length == null || Length.length == 0)
        return (false);

    return String.substr((Start - 1), Length);
}


function InStr(String1, String2) {
    var a = 0;

    if (String1 == null || String2 == null)
        return (false);

    String1 = String1.toLowerCase();
    String2 = String2.toLowerCase();

    a = String1.indexOf(String2);
    if (a == -1)
        return 0;
    else
        return a + 1;
}

function OK() {
    var str;
    str = '';

    try {

        str = document.getElementById("Centro1_ParteCentrale1_IscrzioneAziendale1_Coor").value;

    }
    catch (e) {
        try {
            
            str = document.getElementById("Centro1_ParteCentrale1_IscrizioneAssociazioni1_Coor").value;
        }
        catch (e) { } 
    }
   
    str = str.replace(/\;/g, "\n");
   
    if (str != '') { document.getElementById("memo").value = str; }
    if (str != '') {
        if (str.length > 50) {

            drawFromText();
        }
        else { drawPunto(); }
    }
}

//var str;
//str = '';

//try {
//    
//    str = document.getElementById("Centro1_ParteCentrale1_IscrzioneAziendale1_Coor").value;
//    
//   }
//catch (e) {
//    try {
//        alert("eRR")
//        alert(e.message)
//        
//    
//    str = document.getElementById("Centro1_ParteCentrale1_IscrizioneAssociazioni1_Coor").value; } 
//catch (e) { } }
//alert(str)
//if (str != '') { document.getElementById("memo").value = str; }
//if (str != '') {
//    if (str.length > 50) {

//        drawFromText();
//    }
//    else { drawPunto(); }
//}

function createElem(opt_className, opt_html, opt_tagName) {
    var tag = opt_tagName || "div";
    var elem = document.createElement(tag);
    if (opt_html) elem.innerHTML = opt_html;
    if (opt_className) elem.className = opt_className;
    return elem;
}

function draggablePopup(contents, opt_options) {
    var opts = opt_options || {};
    var popup = createElem("draggable-popup");
    popup.style.width = opts.width || "240px";
    popup.style.top = opts.top || "1600px";
    popup.style.left = opts.left || "640px";
    popup.style.padding = opts.padding || "10px";
    popup.style.paddingTop = "0px";
    popup.style.visibility = "hidden";
    var me = this;
    popup.onmouseover = function() { GEvent.trigger(me, 'mouseover') };
    popup.onmouseout = function() { GEvent.trigger(me, 'mouseout') };
    var header = createElem("draggable-popup-header");
    header.style.textAlign = "right";
    var closetext = opts.closeText || "Close[x]";
    var close = createElem("draggable-popup-close", closetext, "a");
    close.onclick = function() { popup.style.visibility = "hidden" };
    header.appendChild(close);
    var popupContents = createElem("draggable-popup-contents", contents);
    popup.appendChild(header);
    popup.appendChild(popupContents);
    document.getElementsByTagName("body")[0].appendChild(popup);
    this.dragObject = new GDraggableObject(popup);
    this.popup = popup;
    this.show = function() { popup.style.visibility = "visible" };
    this.hide = function() { popup.style.visibility = "hidden" };
}