﻿/*custom control*/
function SaveControl() {}

SaveControl.prototype = new GControl();

SaveControl.prototype.initialize = function(map) {
    var container = document.createElement("div");

    var saveInDiv = document.createElement("div");
    this.setButtonStyle_(saveInDiv);
    container.appendChild(saveInDiv);
    saveInDiv.appendChild(document.createTextNode("Opslaan"));
    GEvent.addDomListener(saveInDiv, "click", function() {
    getCoordinates();
});

    var clearInDiv = document.createElement("div");
    this.setButtonStyle_(clearInDiv);
    container.appendChild(clearInDiv);
    clearInDiv.appendChild(document.createTextNode("Leegmaken"));
    GEvent.addDomListener(clearInDiv, "click", function() {
    clearMap();
    });

    map.getContainer().appendChild(container);
    return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
SaveControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
SaveControl.prototype.setButtonStyle_ = function(button) {
    button.style.font = "small Arial";
    button.style.fontSize = "12px";
    button.style.textAlign = "center";
    button.style.cursor = "pointer";
    button.style.background="transparent url(/Images/Bo/bg_input.gif) no-repeat scroll center center";
    button.style.border="0 none";
    button.style.color="#FFFFFF";
    button.style.fontStyle="normal";
    button.style.fontWeight="bold";
    button.style.height="20px";
    button.style.margin="5px 5px 5px 5px";
    button.style.width = "100px";

}

/*google maps init*/
var map;
var markers = [];
var polyShape;
var polyPoints = [];
var bounds = new GLatLngBounds;
var marker;
var encPoint;
var gMode;
var encZoom;
var fillColor = "#cc0011"; // blue fill
var lineColor = "#cc0011"; // black line
var opacity = .8;
var lineWeight = 12;
var baseIcon;
function load(x, y, mode, encP, encZ) {

    gMode = mode;
    if (GBrowserIsCompatible()) {

        baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.image = "/images/3digets.png";
        map = new GMap2(document.getElementById("map"));
        map.enableScrollWheelZoom();
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());

        if (gMode != 'all') {
      
        map.setCenter(new GLatLng(x, y), 13);
        if (gMode == 'pick') {
            marker = new GMarker(new GLatLng(x, y), { draggable: true });
            map.addOverlay(marker);
            GEvent.addListener(marker, 'dragstart', function() { map.closeInfoWindow(); });
            GEvent.addListener(marker, 'dblclick', function() { getCoordinates(); });
        } else {
        //map.addControl(new SaveControl());
        //set polyline
        if (encP != null) {decode(encP, encZ); }             
            GEvent.addListener(map, 'click', mapClick);
        }
    } else {

        //set all points
    map.setCenter(new GLatLng(x, y), 13);

    }
       
        
    }
}
function showMarker(x, y, id, icon,no,naam) {

    var point = new GLatLng(x, y)


        // marker = new GMarker(point, new GIcon(G_DEFAULT_ICON));
    var ico = new GIcon(G_DEFAULT_ICON);

        ico.image = "/images/3digets.png";

        ico.iconSize = new GSize(32, 32);
        opts = {
        "icon": ico,
            "clickable": true,
            "title":''+ naam,
            "labelText": no,
            "labelOffset": new GSize(-6, -32)
        };

        marker = new LabeledMarker(point, opts);
        
 
    
  

    GEvent.addListener(marker, "click", function() {
        for (i = 0; i < markers.length; i++) {
            markers[i].setImage("/Images/3digets.png");
             }
             this.setImage("/Images/3digetsselected.png");
             ShowInfo(id);

             var el = document.getElementById("_" + id);

             var elclasssel = getElementsByClassName("digitsballoon selected");
             for (s = 0; s < elclasssel.length; s++) {

                 elclasssel[s].className = "digitsballoon";
             }


             var elclass = getElementsByClassName("digitsballoon");
             for (c = 0; c < elclass.length; c++) {

                 if (elclass[c].id == el.id) {
                     elclass[c].className = "digitsballoon selected";
                 }
             }

    });

    markers.push(marker);
    map.addOverlay(marker);
    //map.panTo(point);
	bounds.extend(point);
	    if (map.getBoundsZoomLevel(bounds) > 13) {
        map.setCenter(bounds.getCenter(), 13);
    } else {
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	}

}
function getElementsByClassName(classname, node) {

    if (!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for (var i = 0, j = els.length; i < j; i++)
        if (re.test(els[i].className)) a.push(els[i]);
    return a;

}

function changeMarker(ond,naam) 
{

   
    var el = document.getElementById("_" + ond);

    var elclasssel = getElementsByClassName("digitsballoon selected");
    for (s = 0; s < elclasssel.length; s++) {

        elclasssel[s].className = "digitsballoon";
    }
    
        
    var elclass = getElementsByClassName("digitsballoon");
    for (c = 0; c < elclass.length; c++) {

        if (elclass[c].id == el.id) {
            elclass[c].className = "digitsballoon selected";
        }
    }




    for (i = 0; i < markers.length; i++) {
        if (markers[i].getTitle() ==  naam) {
        markers[i].setImage("/Images/3digetsselected.png");
		map.panTo(markers[i].getPoint());
        }else{
        markers[i].setImage("/Images/3digets.png");
        }
    }

}



function createMarker(x, y, html, icon) {
    var point = new GLatLng(x, y)
        if (icon == 'null') {
            marker = new GMarker(point, new GIcon(G_DEFAULT_ICON));
        } else {
            var ico = new GIcon(G_DEFAULT_ICON);
            ico.image = icon;
            ico.shadow = icon;
            ico.iconSize = new GSize(39, 34);
            ico.shadowSize = new GSize(39, 34);
            ico.iconAnchor = new GPoint(9, 34);
            ico.infoWindowAnchor = new GPoint(9, 2);
            marker = new GMarker(point, ico);
        }

    bounds.extend(point);
    if (map.getBoundsZoomLevel(bounds) > 13) {
        map.setCenter(bounds.getCenter(), 13);
    } else {
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    }

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
    });


    map.addOverlay(marker);



}

// mapClick - Handles the event of a user clicking anywhere on the map
// Adds a new point to the map and draws either a new line from the last point
// or a new polygon section depending on the drawing mode.
function mapClick(marker, clickedPoint) {
    // Push onto polypoints of existing polygon
    polyPoints.push(clickedPoint);
    drawCoordinates();
}


// Clear current Map
function clearMap() {
    map.clearOverlays();
    polyPoints = [];
    markers = [];
}

// drawCoordinates
function drawCoordinates() {
    //Re-create Polyline/Polygon
    polyShape = new GPolyline(polyPoints, lineColor, lineWeight, opacity);
    map.clearOverlays();
    // Grab last point of polyPoints to add marker
    marker = new GMarker(polyPoints[polyPoints.length - 1]);
    map.addOverlay(marker);
    map.addOverlay(polyShape);
}

function getCoordinates() {
    if (gMode == 'pick') {
    var arr = marker.getPoint().toString().split(',');

        saveit(arr[1].replace(')', '') * 60, arr[0].replace('(', '') * 60);
    } else {
    createEncodings()

    }
}
//Encode points
function createEncodings() {
    var i = 0;

    var plat = 0;
    var plng = 0;

    var encoded_points = "";
    var encoded_levels = "";

    for (i = 0; i < polyPoints.length; ++i) {

        var point = polyPoints[i];
        
        //alert(map.getZoomLevel());
        var lat = point.y;
        var lng = point.x;
      // var level = map.getZoomLevel(3);
        var level = 3
        var late5 = Math.floor(lat * 1e5);
        var lnge5 = Math.floor(lng * 1e5);

        dlat = late5 - plat;
        dlng = lnge5 - plng;

        plat = late5;
        plng = lnge5;

        encoded_points += encodeSignedNumber(dlat) + encodeSignedNumber(dlng);
        encoded_levels += encodeNumber(level);
    }

    saveit(encoded_points, encoded_levels);
}

// Encode a signed number in the encode format.
function encodeSignedNumber(num) {
    var sgn_num = num << 1;

    if (num < 0) {
        sgn_num = ~(sgn_num);
    }

    return (encodeNumber(sgn_num));
}

// Encode an unsigned number in the encode format.
function encodeNumber(num) {
    var encodeString = "";

    while (num >= 0x20) {
        encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
        num >>= 5;
    }

    encodeString += (String.fromCharCode(num + 63));
    return encodeString;
}

// Decode an encoded levels string into a list of levels.
function decodeLevels(encoded) {
    var levels = [];

    for (var pointIndex = 0; pointIndex < encoded.length; ++pointIndex) {
        var pointLevel = encoded.charCodeAt(pointIndex) - 63;
        levels.push(pointLevel);
    }

    return levels;
}

// Decode the supplied encoded polyline and levels.
function decode(polyline, zoom) {
    var encoded_points = new String(polyline);
    var encoded_levels = new String(zoom);

    if (encoded_points.length == 0 || encoded_levels.length == 0) {
        return;
    }

    var enc_points = decodeLine(encoded_points);
    var enc_levels = decodeLevels(encoded_levels);

    if (enc_points.length == 0 || enc_levels.length == 0) {
        return;
    }

    if (enc_points.length != enc_levels.length) {
        alert('Point count and level count do not match');
        return;
    }
    var arr = [];
    for (var i = 0; i < enc_points.length; ++i) {
        var x = enc_points[i][0]
        var y = enc_points[i][1]
        arr.push(new GLatLng(x, y));

    }
    var polyline = new GPolyline(arr, "#cc0011", 12);
    map.addOverlay(polyline);

}


// Decode an encoded polyline into a list of lat/lng tuples.
function decodeLine(encoded) {
    var len = encoded.length;
    var index = 0;
    var array = [];
    var lat = 0;
    var lng = 0;

    while (index < len) {
        var b;
        var shift = 0;
        var result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        array.push([lat * 1e-5, lng * 1e-5]);
    }

    return array;
}
/*geocoder*/
var geocoder = new GClientGeocoder();
function showAddress(city) {
    var address = document.getElementById("txtMapsStraatenNr").value;
    var addr = address + ', ' + city;
    geocoder.getLatLng(addr,
    function(point) {
        if (!point) {
            alert(addr + " niet gevonden!");
        } else {
            map.clearOverlays();
            map.setCenter(point, 15);
            //Re-create Polyline/Polygon
            polyShape = new GPolyline(polyPoints, lineColor, lineWeight, opacity);
            map.clearOverlays();
            // Grab last point of polyPoints to add marker
            marker = new GMarker(point, { draggable: true });
            map.addOverlay(marker);

            if (gMode == 'pick') {
                GEvent.addListener(marker, 'dragstart', function() { map.closeInfoWindow(); });
                GEvent.addListener(marker, 'dblclick', function() { getCoordinates(); });
            }
            else {
                map.addOverlay(polyShape);
            }


        }
    }
  );
}

