﻿/*
load gmap
*/
$(window).load(function() {
    initialize();
});

/*
unload gmap
*/
$(window).unload(function() {
    GUnload();
});

/*
init gmap
*/
var centerPoint = null;
var centerMarker = null;
var markerIcon = null;
var zoom = 9;
var map = null;

var bounds = null;
var markers = [];
var currentMarker = null;

var $keyword;
var $locations;
var $cbxTypes;

var markersByFilter = [];
var count = 200;

function initialize() {
    if (GBrowserIsCompatible()) {
        centerPoint = new GLatLng(52.3738007, 4.8909347); // Amsterdam
        centerMarker = new GMarker(centerPoint);

        markerIcon = new GIcon(G_DEFAULT_ICON);
        markerIcon.image = "/Template/RootSite/BinaryResource/Assets/map/y.png";
        markerIcon.iconSize = new GSize(20, 20);
        markerIcon.shadow = "/Template/RootSite/BinaryResource/Assets/map/y-shadow.png";
        markerIcon.shadowSize = new GSize(49, 22);
        markerIcon.iconAnchor = new GPoint(6, 20);
        markerIcon.infoWindowAnchor = new GPoint(15, 2);

        map = new GMap2(document.getElementById("map"));
        map.setCenter(centerPoint, zoom);
        map.enableContinuousZoom();
        map.enableDoubleClickZoom();
        map.addControl(new GLargeMapControl3D());

        bounds = new GLatLngBounds();

        // load element
        $keyword = $("#keyword");
        $locations = $("#locations");
        $cbxTypes = $("input[name^='cbxType']");
        $cbxTypes.each(function() {
            $(this).click(filter);
        });

        // load locations json
        loadLocationsJson();

        $keyword.placeholder({ blankSubmit: true });

        if (window.t && t != '') {
            $cbxTypes.val([t]);
        }

        filter(s);
    }
}

/*
load all locations and init all markers
*/
function loadLocationsJson() {
    if (map) {
        for (var i = 0; i < locationsJson.length; i++) {
            var location = locationsJson[i];
            if (location != null) {
                var point = new GLatLng(location["Lat"], location["Lng"]);
                var defaultRadius = 200 * 1000 // only show locations with 200KM
                var distance = point.distanceFrom(centerPoint);
                if (distance < defaultRadius) {
                    // distance with Amsterdam
                    location["Distance"] = distance;

                    var marker = new GMarker(point, { icon: markerIcon, title: location["Title"] });
                    marker.initVisible = true;
                    if (location["Type"].toLowerCase().indexOf($cbxTypes.filter(':checked').val()) < 0)
                        marker.initVisible = false;
                    markers[i] = marker;
                    //map.addOverlay(marker);

                    markersByFilter.push(markers[i]);

                    bindMarkerClick(marker, location);
                    addLocation(location, i);
                    bounds.extend(point);
                }
            }
        }

        zoom = map.getBoundsZoomLevel(bounds);

        // load markers
        var times = parseInt((markersByFilter.length - 1) / count) + 1;
        for (var i = 0; i < times; i++) {
            // delay seconds: 0, 5, 7, 9
            var delay = 0;
            if (i != 0) {
                delay = (2 * i + 3) * 1000;
            }
            setTimeout("addMarkers(" + i + ")", delay);
        }

        // fit map to show all markers
        map.closeInfoWindow();
        if (markers.length > 0) {
            map.setZoom(zoom);
        }

        var center = bounds.getCenter();
        map.setCenter(center);
    }
}

function addMarkers(currentTimes) {
    var start = currentTimes * count;
    var end = (currentTimes + 1) * count;
    var markers = markersByFilter.slice(start, end);
    for (var i = 0; i < markers.length; i++) {
        map.addOverlay(markers[i]);
        if (!markers[i].initVisible)
            markers[i].hide();
    }
}

/*
bind marker click
*/
function bindMarkerClick(marker, location) {
    GEvent.addListener(marker, "click", function() {
        var typeHtml = "";
        var types = location["Type"].split(',');
        for (var i = 0; i < types.length; i++) {
            var type = types[i];
            typeHtml += "<li>" + type + "</li>";
        }

        var detailHtml = "";
        if (location["Type"].toLowerCase() == "verzekeringsadviseurs")
            detailHtml = "<div class='location'>" +
                                  "<div class='location-title'>Verzekeringsadviseur</div>" +
                                  "<p>" + location["Text"] + "<br/><br/></p>" +
                                  "<div class='location-title'>Contactgegevens</div><p>" +
                                  ($.trim(location["Photo"]) == "" ? "<img src='/cms/images/no-thumb.gif' width='94' height='125' style='float:left;' />" : "<img width='94' height='125' src='" + location["Photo"].split(',')[0] + "' style='float:left;' />") +
                                  "<span style='display:block;float:left;width:180px; margin:10px 0 0 10px;'>" + location["Title"] + "<br/>" + location["Tel"] + "<br/>" + "<a class='link-new' href='mailto://" + location["Email"] + "'><span class='text'>" + location["Email"]+"</span></a>" + "</span>" +
                                "</div>";
        else
            detailHtml = "<div class='location'>" +
                                  "<div class='location-title'>" + location["Title"] + "</div>" +
                                  "<p>" + location["Text"] + "<br/><br/></p>" +
                                  "<div class='location-title'>Contactgegevens</div><p>" +
                                  "<span>" + location["Title"] + "<br/>" + location["Address"] + "<br/>" + location["Postcode"] + "<br/>" + location["City"] + "<br/>" + location["Tel"] + "<br/>" + location["Url"] + "</span>" +
                                    "<p class='location-route-title' style='clear:left;'>Routebeschrijving:</p>" +
                                    "<p>Uw woonplaats / adres:</p>" +
                                    "<div class='search-route-form'>" +
                                        "<form id='searchRouteForm' target='_blank' method='get' action='http://maps.google.nl/maps'>" +
                                            "<input type='text' id='saddr' name='saddr' class='placeholder' placeholder='woonplaats of adres' value='" + location["Postcode"] + " " + location["City"] + "' onfocus='saddrFocus(this)' onblur='saddrBlur(this)' />" +
                                            "<input type='hidden' value='" + location["Lat"] + "," + location["Lng"] + "' name='daddr'/>" +
                                            "&nbsp;&nbsp;<a href='javascript:void(0)' onclick='submitSearchRoute()' class='btn button-gh20'><span class='button-gh20-in'>vind</span></a>" +
                                        "</form>" +
                                    "</div>" +
                                    "<div>bijv: Amsterdam of 1399 AA</div>" +
                                "</div>";

        marker.openInfoWindowHtml(detailHtml);
        currentMarker = marker;
    });
}

/*
trigger marker click
*/
function triggerMasterClick(index) {
    if (!markers[index]) return;
    map.setZoom(12);
    GEvent.trigger(markers[index], "click");
}

/*
rebuild locations
*/
function rebuildLocations() {
    $locations.html("");
}

/*
add location
*/
function addLocation(location, index) {
    if (location) {
        var type = location["Type"].toLowerCase();
        var locationHtml = "<li><a href='javascript:void(0)' onclick='triggerMasterClick(" + index + ")' class='link-used'><span style='float:left;'>&gt;</span><span class='text'>" + location["Title"] + "</span></a>";
        locationHtml += "<p style='padding-left:15px'>" + (type == "verzekeringsadviseurs" ? "Verzekeringsadviseur" : "Assurantietussenpersoon") + "<br/>";
        if (type == 'assurantietussenpersoon') {
            locationHtml += location["Street"] + "<br/>";
            locationHtml += location["Postcode"] + "<br/>";
            locationHtml += location["City"] + "<br/>";
            locationHtml += location["Tel"];
            if (location["Url"] != "") {
                locationHtml += "<br/>" + location["Url"];
            }
        } else {
            locationHtml += location["Tel"] + "<br/>";
            locationHtml += location["Email"]
        }
        locationHtml += "</p>";
        locationHtml += "</li>";

        $locations.append(locationHtml);
    }
}

/*
get keyword
*/
function getKeyWord() { // get keyword
    var keyword = $keyword.val();
    keyword = $.trim(keyword.toLowerCase());
    if (keyword == "uw postcode") {
        keyword = "";
    } else {
        var isPostCode = /^([0-9]{4}((\s)?[a-zA-Z]{2})?)?$/.test(keyword); // 1234 AA
        if (isPostCode) {
            keyword = keyword.replace(" ", "");
        }
        else {
            alert('Dit is geen geldige postcode!');
            $keyword.val('');
            keyword = "";
        }
    }

    return keyword;
}


/*
get locations by typeIndexs
*/
function getLocationsByType(type) {
    var locationsByType = locationsJson.slice();
    for (var i = 0; i < locationsByType.length; i++) {
        if (locationsByType[i] != null) {
            var vType = locationsByType[i]["Type"].toLowerCase();
            var containType = vType.indexOf(type) >= 0;
            if (!containType) {
                locationsByType[i] = null;
            }
        }
    }

    return locationsByType;
}

/*
filter
*/
var locationsByFilter = null;
function filter(id) {
    var type = $cbxTypes.filter(':checked').val();
    locationsByFilter = getLocationsByType(type);
    var markIndex = 0;

    var keyword = getKeyWord();
    if (keyword != "") { // search
        // search point with keyword
        if (type == 'assurantietussenpersoon') {
            var geocoder = new GClientGeocoder();
            geocoder.setBaseCountryCode("NL");
            geocoder.getLatLng(keyword, function(searchPoint) {
                if (searchPoint != null) { // point with keyword
                    for (var i = 0; i < locationsByFilter.length; i++) {
                        var location = locationsByFilter[i];
                        if (location != null) {
                            var point = new GLatLng(location["Lat"], location["Lng"]);
                            var radius = 50 * 1000 // all the locations within a radius of 50KM
                            var distance = point.distanceFrom(searchPoint);
                            if (distance < radius) {
                                locationsByFilter[i]["Distance"] = distance;
                            } else {
                                locationsByFilter[i] = null;
                            }

                            if (location["UUID"] == id)
                                markIndex = i;
                        }
                    }

                    sortByRadius();
                }
            });
        } else {
            var p4 = parseInt(keyword.substr(0, 4), 10);
            for (var i = 0; i < locationsByFilter.length; i++) {
                var location = locationsByFilter[i];
                if (location != null) {
                    var rayon = location["Rayon"];
                    if (!rayon || rayon == '') { locationsByFilter[i] = null; continue; }
                    var rayons = rayon.split(',');
                    var inRange = false;
                    for (var r = 0; r < rayons.length; r++) {
                        var bound = rayons[r].split('-');
                        if (parseInt(bound[0], 10) <= p4 && p4 <= parseInt(bound[1], 10)) {
                            inRange = true;
                            r = rayons.length;
                        }
                    }
                    if (!inRange) {
                        locationsByFilter[i] = null;
                    }

                    if (location["UUID"] == id)
                        markIndex = i;
                }
            }
            sortByCity();
        }

        // search will back to default mode
        if (currentMarker) {
            map.closeInfoWindow();
            if (markers.length > 0) {
                map.setZoom(zoom);
            }

            var center = bounds.getCenter();
            map.setCenter(center);

            currentMarker = null;
        }
    } else { // filter
        for (var i = 0; i < locationsByFilter.length; i++) {
            if (locationsByFilter[i]) {
                if (locationsByFilter[i]["UUID"] == id)
                    markIndex = i;
            }
        }
        sortByCity();
    }
    if (markIndex > 0)
        setTimeout(function() { triggerMasterClick(markIndex); }, 3000);
}

/*
sort by city(default)
*/
function sortByCity() {
    rebuildLocations();
    if (locationsByFilter != null) {
        for (var i = 0; i < locationsByFilter.length; i++) {
            var location = locationsByFilter[i];
            var marker = markers[i];
            if (location != null) {
                if (marker != null && marker.isHidden()) {
                    marker.show();
                }
                addLocation(location, i);
            } else {
                if (marker != null) {
                    marker.hide();
                }
            }
        }
    }
}

/*
sort by radius
*/
var sortByRadiusLocationsFilter = null; // locations filter sort by radius
var sortByRadiusLocationsFilterIndexs = null; // locations filter index sort by radius

function sortByRadius() {
    if (locationsByFilter != null) {
        sortByRadiusLocationsFilter = locationsByFilter.slice(); // copy locationsByFilter
        sortByRadiusLocationsFilterIndexs = new Array(sortByRadiusLocationsFilter.length);
        for (var i = 0; i < sortByRadiusLocationsFilterIndexs.length; i++) {
            sortByRadiusLocationsFilterIndexs[i] = i;
        }

        for (var i = 0; i < sortByRadiusLocationsFilter.length; i++) { // sort by radius
            for (var j = sortByRadiusLocationsFilter.length - 1; j > i; j--) {
                if (sortByRadiusLocationsFilter[j] && sortByRadiusLocationsFilter[j - 1]) {
                    if (sortByRadiusLocationsFilter[j]["Distance"] >= sortByRadiusLocationsFilter[j - 1]["Distance"]) {
                        continue;
                    }
                } else if (sortByRadiusLocationsFilter[j]) {
                    continue;
                }

                // swap
                var temp = sortByRadiusLocationsFilter[j];
                sortByRadiusLocationsFilter[j] = sortByRadiusLocationsFilter[j - 1];
                sortByRadiusLocationsFilter[j - 1] = temp;

                var tempIndex = sortByRadiusLocationsFilterIndexs[j];
                sortByRadiusLocationsFilterIndexs[j] = sortByRadiusLocationsFilterIndexs[j - 1];
                sortByRadiusLocationsFilterIndexs[j - 1] = tempIndex;
            }
        }

        rebuildLocations();

        for (var i = 0; i < sortByRadiusLocationsFilterIndexs.length; i++) {
            var location = sortByRadiusLocationsFilter[i];
            var index = sortByRadiusLocationsFilterIndexs[i];
            var marker = markers[index];
            if (location != null) {
                if (marker != null && marker.isHidden()) {
                    marker.show();
                }

                addLocation(location, index);
            } else {
                if (marker != null) {
                    marker.hide();
                }
            }
        }
    }
}

/*
for location pop placeholder
*/
function saddrFocus(input) {
    var $input = $(input);
    if ($input.hasClass('placeholder')) {
        $input.val("");
        $input.removeClass('placeholder');
    }
    return false;
}

/*
for location pop placeholder
*/
function saddrBlur(input) {
    var $input = $(input);
    if ($.trim($input.val()) == "") {
        $input.addClass("placeholder");
        var placeholder = $input.attr("placeholder");
        $input.val(placeholder);
    }
}

/*
for location pop placeholder
*/
function submitSearchRoute() {
    var $saddr = $("#saddr");
    var isPlaceHolder = false;
    if ($saddr[0]) {
        isPlaceHolder = $saddr.hasClass("placeholder");
        if (isPlaceHolder) {
            $saddr.val("");
        }
    }

    document.forms["searchRouteForm"].submit();
    return false;
}

$(function() {
    // show tip
    $('span.icon-question').bt({
        positions: ['right'],
        contentSelector: "$(this).children().html()",
        spikeGirth: 0,
        spikeLength: 0,
        shadowColor: '#8A8474'
    });
});
