﻿/*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 routemap;
var encPoint;
var gMode;
var encZoom;
var fillColor = "#345684"; // blue fill
var lineColor = "#345684"; // black line
var opacity = .6;
var lineWeight = 11;
var baseIcon;
var gdird;
var tmode = G_TRAVEL_MODE_DRIVING;
function load(x, y, mode, encP, encZ) {

    gMode = mode;
    if (GBrowserIsCompatible()) {

        baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.image = "/images/company.png";
        map = new GMap2(document.getElementById("map"));
        map.enableScrollWheelZoom();
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());

        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "addoverlay", onGDirectionsLoaded);
        GEvent.addListener(gdir, "error", handleErrors);

        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)
    var ico = new GIcon(G_DEFAULT_ICON);
    if (icon == 'null' || icon == '') {
        icon = "company";
    }

    ico.image = "/images/" + icon + ".png";
    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);
    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++) {
            var arricon = markers[i].getIcon().image.split("/")
            var sym = arricon[arricon.length - 1].split(".")[0]
            if (sym.lastIndexOf("selected") > 0) { sym = sym.substring(sym.lastIndexOf("selected"), 8) } else { sym = sym }
            markers[i].setImage("/images/" + sym + ".png");

        }
        arricon = this.getIcon().image.split("/")
        sym = arricon[arricon.length - 1].split(".")[0]
        if (sym.lastIndexOf("selected") > 0) { sym = sym.substring(sym.lastIndexOf("selected"), 8) } else { sym = sym }
        this.setImage("/images/" + icon + "selected.png");
        ShowInfo(id);

           var elclasssel = getElementsByClassName(" selected");
           for (s = 0; s < elclasssel.length; s++) {
             
                elclasssel[s].className = elclasssel[s].className.substring(0,elclasssel[s].className.length - 9);
            }

        var el = document.getElementById("_" + id);
        el.className = el.className + " selected";



    });

    markers.push(marker);
    map.addOverlay(marker);
        //map.panTo(point);
    bounds.extend(point);

    if (map.getBoundsZoomLevel(bounds) > 14) {
        map.setCenter(bounds.getCenter(), 14);
    } 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, icon,naam) {
    if (icon == 'null' || icon == '') {
        icon = "company"
    }


    var el = document.getElementById("_" + ond);

    var elclasssel = getElementsByClassName(" selected");
    for (s = 0; s < elclasssel.length; s++) {
        elclasssel[s].className = elclasssel[s].className.substring(0, elclasssel[s].className.length - 9);
    }


    el.className = "icon_" + icon + " selected";

    for (i = 0; i < markers.length; i++) {

        if (markers[i].getTitle() == naam) {
            markers[i].setImage("/images/" + icon + "selected.png");
            map.panTo(markers[i].getPoint());
        } else {
            var arricon = markers[i].getIcon().image.split("/")
            var sym = arricon[arricon.length - 1].split(".")[0]
            if (sym.lastIndexOf("selected") > 0) { sym = sym.substring(sym.lastIndexOf("selected"), 8) } else { sym = sym }
            markers[i].setImage("/images/" + sym + ".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) > 14) {
          map.setCenter(bounds.getCenter(), 14);
      } 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 = [];
    bounds = new GLatLngBounds;
}

// 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, lineColor, 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;
}
function clearMarkers() {
    map.clearOverlays();

    bounds = new GLatLngBounds;
}
/*routeplanner*/
function check(val) {
    tmode = val;

}
function clearDirections() {

    //  var div = document.getElementById('directions');
    //  div.innerHTML = '';
    //  div.style.background = "none";
    //  document.getElementById('dirwrap').style.display = 'none';
}
function MakeDirDivVisible() {
    // var div = document.getElementById('directions');
    //  div.style.background = "#fff";

    //   document.getElementById('dirwrap').style.display = 'block';
}

function SetRouteplanner(dir) {

    direction = dir;
}
function setDirections(locale) {
   // clearMarkers();
    //   MakeDirDivVisible();

    var fromAddress;
    var toAddress;


    fromAddress = document.getElementById("txtFromStreet").value + ' ' + document.getElementById("txtFromPostalCode").value + ' ' + document.getElementById("txtFromCity").value + ", belgie";
    toAddress = document.getElementById("txtToStreet").value + ' ' + document.getElementById("txtToPostalCode").value + ' ' + document.getElementById("txtToCity").value + ", belgie";

    gdir.load("from: " + fromAddress + " to: " + toAddress,
                    { "locale": locale, "travelMode": tmode });



}

function handleErrors() {
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("Adres niet gevonden.");
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

    else alert("An unknown error occurred.");

}
function onGDirectionsLoad() {

}
function onGDirectionsLoaded() {
    // open a welcome message as soon as the window loads
    lcpbox.open({
    content: document.getElementById("routeresults").innerHTML,
        player: "html",
        title: "Routebeschrijving",
        height: 450,
        width: 600
    });

}

/*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);
            }


        }
    }
  );
}

