﻿//extenson for Array to check whether it contains a value
Array.prototype.has = function(v, i) {
    for (var j = 0; j < this.length; j++) {
        if (this[j] == v) return (!i ? true : j);
    }
    return false;
}

google.load("maps", "2");

var map;
var searchMarker;
var allMarkers = [];
var checkBoxes = $('#service-filters input');

$(document).ready(function() {
    $('#map').ajaxError(function() {
        $(this).html('<h2 style="color:red;">There was a problem fetching the data for the map.  Please try again later</h2>');
    });
    if (google.maps.BrowserIsCompatible()) {
        var options = {
            beforeSubmit: preFind,
            success: findNearestHome,
            url: '/map/FindNearestHomes/',
            type: 'post',
            dataType: 'json'
        };

        $('#search-carehomes').ajaxForm(options);

        $.getJSON("/map/data", { cache: false }, initialise);
        $('#service-filters input').each(function() {
            var chk = $(this);
            chk.click(function() {
                filterServices();
            });
        });
    }
});

function preFind() {
    if (searchMarker) map.removeOverlay(searchMarker);
}

function findNearestHome(data) {
    var latlng = new google.maps.LatLng(data[0].SearchCoordinates.Latitude, data[0].SearchCoordinates.Longitude)
    searchMarker = new google.maps.Marker(latlng);
    map.addOverlay(searchMarker);

    map.panTo(latlng);

    var container = $('<ol></ol>');
    $(data).each(function(i) {
        var home = data[i].CareHome;

        var liContainer = $('<li></li>');

        var anchorContainer = $('<a></a>');
        anchorContainer.html(home.Name + ', ' + home.Town);
        anchorContainer[0].href = home.Url;

        var spanContainer = $('<span></span>');
        spanContainer.html(' (' + data[i].Distance + ' miles)')

        liContainer.append(anchorContainer);
        liContainer.append(spanContainer);
        container.append(liContainer);
    });

    $('#nearest-homes').html(container);
    $('#nearest-homes').prepend('<h3>Nearest homes to you:</h3>');
}

function initialise(mapData) {
    // create the map           
    map = new google.maps.Map2($("#map")[0]);
    map.addControl(new google.maps.SmallMapControl());
    map.addControl(new google.maps.MapTypeControl());
    map.setMapType(G_HYBRID_MAP);

    //centre the map on London
    var zoomIndex = 7;
    map.setCenter(new google.maps.LatLng(52.0, -0.9), zoomIndex);  // Roughly central London, to include as many homes as possible on the home (Norwich doesn't fit in).

    //add all the carehome markers
    $.each(mapData.carehomes, function(i, carehome) {
        setupLocationMarker(map, carehome);
    });

    //do a search if need be
    if ($('#searchTerm').val() != "") {
        $('#Postcode').val($('#searchTerm').val());
        $('#search-carehomes').submit();
    }
}

function filterServices() {
    var visibleMarkers = [];
    map.clearOverlays();
    for (var i = 0; i < allMarkers.length; i++) {
        $('#service-filters input').each(function() {
            var serviceName = this.id.substring(3, this.id.length);
            if ($(this).is(':checked') && allMarkers[i][serviceName]) {
                //we want to keep this marker
                visibleMarkers.push(allMarkers[i]);
            }
        });
        if (visibleMarkers.has(allMarkers[i])) {
            map.addOverlay(allMarkers[i]);
        }
    }
}

function setupLocationMarker(map, home) {
    var latlng = new google.maps.LatLng(home.Coordinates.Latitude, home.Coordinates.Longitude);

    var careHomeIcon = new GIcon();
    careHomeIcon.image = "/assets/img/map/marker.png";
    careHomeIcon.shadow = "/assets/img/map/shadow.png";
    careHomeIcon.iconSize = new GSize(20, 34);
    careHomeIcon.shadowSize = new GSize(62, 40);
    careHomeIcon.iconAnchor = new GPoint(9, 34);
    careHomeIcon.infoWindowAnchor = new GPoint(10, 34);

    var markerOptions = { icon : careHomeIcon };


    var marker = new google.maps.Marker(latlng, markerOptions);
    map.addOverlay(marker);
    allMarkers.push(marker);

    for (var i = 0; i < home.careservices.length; i++) {
        var serviceName = home.careservices[i].name;
        if (!marker[serviceName]) marker[serviceName] = true;
    }
    marker[name] = home.name;

    // add a marker click event
    google.maps.Event.addListener(marker, "mouseover", function(latlng) {

        // show the name and image on the page
        //                $("#info").text(location.Name);
        //                $("#image")[0].src = "/assets/img/" + location.Image;
        // open the info window with the location name
        //map.openInfoWindow(latlng, $("<p></p>").text(bubbleText)[0]);
        marker.openInfoWindowHtml(getBubbleContent(home));
    });
}

function getBubbleContent(home) {
    var bubbleContent="<div class=\"carehomeBubble\">";
    bubbleContent += "<h4><a href=\"" + home.URL + "\">";
    bubbleContent += home.name;
    bubbleContent += "</a></h4><div style=\"width:160px;float:left;\">";
    if (home.GoogleMapBubble != "") bubbleContent += "<br />" + home.GoogleMapBubble;
    bubbleContent += "</div><div style=\"width:50px;float:right;\">"
    //bubbleContent += "<img src=\"" + home.Photo + "\">";
    bubbleContent += "</div></div>";

    return bubbleContent;
}