﻿/// <reference path="../../../../../Javascript/jquery-1.3.2.min.js" />
/// <reference path="jquery.pagination_ex.js" />
/// <reference path="tooltip.js" />

/*
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 $sortByCity;
var $srotByAddress;
var $sortByRadius;
var $locations;
var $cbxTypes;
var locationResult = [];

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");
        $sortByCity = $("#sortByCity");
        $sortByAddress = $("#sortByAddress");
        $sortByRadius = $("#sortByRadius");
        $locations = $("#locations");
        $cbxTypes = $("input[id^='cbxType-']");
        $cbxTypes.each(function () {
            $(this).click(filter);
        });

        if ($.trim(s) != "") { // search
            $keyword.val(s);
        } else { // keyword placeholder
            $keyword.placeholder({ blankSubmit: true });
        }

        // load locations json
        loadLocationsJson();
        // clean dirty data or search
        filter();
    }
}

/*
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"] });
                    var marker = new GMarker(point, { icon: markerIcon });
                    markers[i] = marker;
                    map.addOverlay(marker);

                    bindMarkerClick(marker, location);

                    //addLocation(location, i);
                    bounds.extend(point);
                }
            }
        }

        // initPagination();

        // fit map to show all markers
        zoom = map.getBoundsZoomLevel(bounds);
        map.closeInfoWindow();
        if (markers.length > 0) {
            map.setZoom(zoom);
        }

        var center = bounds.getCenter();
        map.setCenter(center);
    }
}

/*
bind marker click and mouseover out
*/
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>";
        }

        //textbox
        var txtHtml = "<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='woonplaats of adres' 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' style='vertical-align: top;'><span class='button-gh20-in'>vind</span></a>" +
                                    "</form>" +
                                    "</div>" +
                                    "<div style='color: #4B463A;'>bijv: Amsterdam of 1399 AA</div>";
        var linkHtml = "<p/><a href='http://maps.google.nl/maps?saddr=&daddr=' target='_blank' style='color:#970F0E;text-decoration:underline'>Plan uw route</a>"

        var tempHtml = "";
        if (location["RouteType"] == "2") {
            tempHtml = linkHtml;
        }
        else {
            tempHtml = txtHtml;
        }

        var detailHtml = "<div class='location'>" +
                                    "<div class='location-title'>" + location["Title"] + "</div>" +

                                    ($.trim(location["MapsThumb"]) == "" ? "<img src='http://yardenuitvaartwensendag.rb2.nl/img/vestigingen/steenbrugge.jpg' />" : "<img width='250' height='150' src='" + location["MapsThumb"] + "'/>") +

                                    "<p class='location-address-title'>Adresgegevens:<p>" +
                                    "<p style='line-height: 16px;'>" + location["Address"] + "</p>" +
                                    "<p style='line-height: 16px;'>" + location["Street"] + "</p>" +
                                    "<p style='line-height: 16px;'>" + location["Postcode"] + " " + location["City"] + "</p>" +

                                    "<p class='location-service-title'>Voorzieningen:</p>" +
                                    "<ul class='location-service'>" + typeHtml + "</ul>" +

                                    "<div class='location-goto'><a href='" + locationUrl + "/" + location["EncodeTitle"] + "' class='btn button-gh25'><span class='button-gh25-in'>Meer informatie</span></a></div>" +
                                    "<p>Alle informatie en mogelijkheden van deze vestiging</p>" +

                                    "<p class='location-route-title'>Routebeschrijving:</p>" +
                                        tempHtml +
                                    "<p class='location-address-title' style='padding-top:15px'>Openbaar vervoer:</p>" +
                                    "<p style='line-height: 16px;'><a target='_blank' href='http://www.9292ov.nl' style='color:#970F0E'>Plan hier uw reis met het OV</a></p>"

        "</div>";

        marker.openInfoWindowHtml(detailHtml);
        currentMarker = marker;
    });

    GEvent.addListener(marker, "mouseover", function () {
        var typeHtml = "<div class='shadow'><div class='maptip'><p>" + location["Title"] + "</p><ul>";
        var types = location["Type"].split(',');
        for (var i = 0; i < types.length; i++) {
            var type = types[i];
            typeHtml += "<li>" + type + "</li>";
        }
        typeHtml += "</ul></div></div>";
        tooltip.show(typeHtml);
        currentMarker = marker;
    });

    GEvent.addListener(marker, "mouseout", function () {
        tooltip.hide();
        currentMarker = marker;
    });
}

/*
trigger marker click
*/
function triggerMasterClick(index) {
    map.setZoom(12);
    GEvent.trigger(markers[index], "click");
}

/*
rebuild locations
*/
function rebuildLocations() {
    locationResult = [];
}



/*
add location
*/
function addLocation(location, index) {
    if (location) {
        locationResult.push({ "location": location, "index": index });
    }
}

/* page */

var perpageitem = 7;
function pageselectCallback(page_index, jq) {
    var start = perpageitem * page_index;
    var end = start + perpageitem;
    end = end <= locationResult.length ? end : locationResult.length;
    var locaionHtml = [];
    for (var i = start; i < end; i++) {
        locaionHtml.push("<li onclick='triggerMasterClick(" + locationResult[i].index + ")'><strong>" + locationResult[i].location.City + "</strong><p>" + locationResult[i].location.Title + "</p></li>");
    }
    $locations.html(locaionHtml.join(""));
    return false;
}

function initPagination() {
    var num_entries = locationResult.length;
    $("#Pagination").pagination(num_entries, {
        callback: pageselectCallback,
        items_per_page: perpageitem
    });
}

/*
get keyword
*/

function getKeyWord() { // get keyword
    var keyword = $keyword.val();
    keyword = $.trim(keyword.toLowerCase());
    if (keyword == "uw plaats of postcode") {
        keyword = "";
        $("#postcodeterm").html("");
    } else {
        keyword = $keyword.val().replace("<", "").replace(">", "");
        $("#postcodeterm").html("U heeft gezocht op <em>" + keyword + "</em>");
        var isPostCode = /^([0-9]{4}(\s)[a-zA-Z]{2})?$/.test(keyword); // 1234 AA
        if (isPostCode) {
            keyword = keyword.replace(" ", "");
        }
    }
    return keyword;
}

/*
get type indexs
*/
var types = ["crematorium", "begraafplaats", "uitvaartcentrum", "zorgvestiging"];
function getTypeIndexs() {
    var typeIndexs = [];
    $cbxTypes.each(function () {
        var $this = $(this);
        if ($this.is(":checked")) {
            var typeIndex = parseInt($this.val());
            typeIndexs.push(typeIndex);
        }
    });

    return typeIndexs;
}

/*
get locations by typeIndexs
*/
function getLocationsByType(typeIndexs) {
    var locationsByType = locationsJson.slice();

    for (var i = 0; i < locationsByType.length; i++) {
        if (locationsByType[i] != null) {
            var type = locationsByType[i]["Type"].toLowerCase();

            var containType = false;
            for (var j = 0; j < typeIndexs.length; j++) {
                var typeIndex = typeIndexs[j];
                if (type.indexOf(types[typeIndex]) >= 0) {
                    containType = true;
                    break;
                }
            }

            if (!containType) {
                locationsByType[i] = null;
            }
        }
    }

    return locationsByType;
}

/*
filter
*/
var locationsByFilter = null;
function filter() {
    var typeIndexs = getTypeIndexs();
    locationsByFilter = getLocationsByType(typeIndexs);

    var keyword = getKeyWord();
    if (keyword != "") { // search
        // search point with keyword
        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;
                        }
                    }
                }

                sortByRadius();
            }
        });

        // 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
        sortByCity();
    }
}

/*
sort by city(default)
*/
function sortByCity() {
    $sortByAddress.removeClass("current");
    $sortByRadius.removeClass("current");
    if (!$sortByCity.hasClass("current")) {
        $sortByCity.addClass("current");
    }

    rebuildLocations();

    if (locationsByFilter == null) {
        for (var i = 0; i < locationsJson.length; i++) {
            var location = locationsJson[i];
            addLocation(location, i);
        }
    } else {
        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();
                }
            }
        }
    }

    initPagination();
}

/*
sort by address
*/
var sortByAddressLocations = null; // locations sort by address
var sortByAddressLocationsIndexs = null; // locations index sort by address
var sortByAddressLocationsFilter = null; // locations filter sort by address
var sortByAddressLocationsFilterIndexs = null; // locations filter index sort by address

function sortByAddress() {
    $sortByCity.removeClass("current");
    $sortByRadius.removeClass("current");
    if (!$sortByAddress.hasClass("current")) {
        $sortByAddress.addClass("current");
    }

    if (locationsByFilter == null) {
        if (!sortByAddressLocations) { // load once
            sortByAddressLocations = locationsJson.slice(); // copy locationsJson
            sortByAddressLocationsIndexs = new Array(sortByAddressLocations.length);
            for (var i = 0; i < sortByAddressLocationsIndexs.length; i++) {
                sortByAddressLocationsIndexs[i] = i;
            }

            for (var i = 0; i < sortByAddressLocations.length; i++) { // sort by adress
                for (var j = sortByAddressLocations.length - 1; j > i; j--) {
                    if (sortByAddressLocations[j]["Title"] < sortByAddressLocations[j - 1]["Title"]) {
                        // swap
                        var temp = sortByAddressLocations[j];
                        sortByAddressLocations[j] = sortByAddressLocations[j - 1];
                        sortByAddressLocations[j - 1] = temp;

                        var tempIndex = sortByAddressLocationsIndexs[j];
                        sortByAddressLocationsIndexs[j] = sortByAddressLocationsIndexs[j - 1];
                        sortByAddressLocationsIndexs[j - 1] = tempIndex;
                    }
                }
            }
        }

        rebuildLocations();

        for (var i = 0; i < sortByAddressLocationsIndexs.length; i++) {
            var location = sortByAddressLocations[i];
            addLocation(location, sortByAddressLocationsIndexs[i]);
        }
    } else {
        sortByAddressLocationsFilter = locationsByFilter.slice(); // copy locationsJson filter
        sortByAddressLocationsFilterIndexs = new Array(sortByAddressLocationsFilter.length);
        for (var i = 0; i < sortByAddressLocationsFilter.length; i++) {
            sortByAddressLocationsFilterIndexs[i] = i;
        }

        for (var i = 0; i < sortByAddressLocationsFilter.length; i++) { // sort by address
            for (var j = sortByAddressLocationsFilter.length - 1; j > i; j--) {
                if (sortByAddressLocationsFilter[j] && sortByAddressLocationsFilter[j - 1]) {
                    if (sortByAddressLocationsFilter[j]["Title"] >= sortByAddressLocationsFilter[j - 1]["Title"]) {
                        continue;
                    }
                } else if (sortByAddressLocationsFilter[j]) {
                    continue;
                }

                // swap
                var temp = sortByAddressLocationsFilter[j];
                sortByAddressLocationsFilter[j] = sortByAddressLocationsFilter[j - 1];
                sortByAddressLocationsFilter[j - 1] = temp;

                var tempIndex = sortByAddressLocationsFilterIndexs[j];
                sortByAddressLocationsFilterIndexs[j] = sortByAddressLocationsFilterIndexs[j - 1];
                sortByAddressLocationsFilterIndexs[j - 1] = tempIndex;
            }
        }

        rebuildLocations();

        for (var i = 0; i < sortByAddressLocationsFilterIndexs.length; i++) {
            var location = sortByAddressLocationsFilter[i];
            var index = sortByAddressLocationsFilterIndexs[i];
            var marker = markers[index];
            if (location != null) {
                if (marker != null && marker.isHidden()) {
                    marker.show();
                }

                addLocation(location, index);
            } else {
                if (marker != null) {
                    marker.hide();
                }
            }
        }
    }

    initPagination();
}

/*
sort by radius
*/
var sortByRadiusLocations = null; // locations sort by radius
var sortByRadiusLocationsIndexs = null; // locations index sort by radius
var sortByRadiusLocationsFilter = null; // locations filter sort by radius
var sortByRadiusLocationsFilterIndexs = null; // locations filter index sort by radius

function sortByRadius() {
    $sortByCity.removeClass("current");
    $sortByAddress.removeClass("current");
    if (!$sortByRadius.hasClass("current")) {
        $sortByRadius.addClass("current");
    }

    if (locationsByFilter == null) {
        if (!sortByRadiusLocations) { // load once
            sortByRadiusLocations = locationsJson.slice(); // copy locationsJson
            sortByRadiusLocationsIndexs = new Array(sortByRadiusLocations.length);
            for (var i = 0; i < sortByRadiusLocationsIndexs.length; i++) {
                sortByRadiusLocationsIndexs[i] = i;
            }

            for (var i = 0; i < sortByRadiusLocations.length; i++) { // sort by radius
                for (var j = sortByRadiusLocations.length - 1; j > i; j--) {
                    if (sortByRadiusLocations[j]["Distance"] < sortByRadiusLocations[j - 1]["Distance"]) {
                        // swap
                        var temp = sortByRadiusLocations[j];
                        sortByRadiusLocations[j] = sortByRadiusLocations[j - 1];
                        sortByRadiusLocations[j - 1] = temp;

                        var tempIndex = sortByRadiusLocationsIndexs[j];
                        sortByRadiusLocationsIndexs[j] = sortByRadiusLocationsIndexs[j - 1];
                        sortByRadiusLocationsIndexs[j - 1] = tempIndex;
                    }
                }
            }
        }

        rebuildLocations();

        for (var i = 0; i < sortByRadiusLocationsIndexs.length; i++) {
            var location = sortByRadiusLocations[i];
            addLocation(location, sortByRadiusLocationsIndexs[i]);
        }
    } else {
        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();
                }
            }
        }
    }

    initPagination();
}

/*
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'
    });
});
