﻿
// define vars

var map; // an instance of GMap2
var markerArray = []; // an array of objects with: latitude, longitude, description
var latlng = []; //an array of instances of GLatLng
var markerMax = 50;


var bounds;
var north;
var east;
var south;
var west;

var type = ""; //white yellow

var JSONResults = [];

//geo-lookup

function geolookup(searchString) {
    var lookup = "guernsey " + searchString;
    if (geocoder) {
        geocoder.getLatLng(
				lookup,
				function(point) {
				    /*
				    if (!point) {
				    // could not find
				    $("#mapmessage").html("<p>No results found for: <strong>" + searchString + "</strong> </p>");
				    } else {
				    // map centered on
				    $("#mapmessage").html("<p>Centred on: <strong>" + searchString + "</strong> </p>");
				    map.panTo(point);
				    }
				    */

				    if (point) {
				        if (point.lat() > 49.407175666458265 && point.lat() < 49.51294975794387 && point.lng() > -2.6968002319335938 && point.lng() < -2.3349380493164062) {
				            // map centered on
				            $("#mapmessagewhere").html("<span>Centred on: <strong>" + searchString + "</strong> </span>");
				            map.panTo(point);
				            return
				        }
				    }

				    // could not find or out of bounds
				    $("#mapmessagewhere").html("<span class='error-text'>No results found for: <strong>" + searchString + "</strong> </span>");

				}
			);
    }
}

//init

function initialize() {

    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("googlemap"));
        map.setCenter(new GLatLng(49.458744, -2.534395), 12);
        map.setUIToDefault();
        createIcons();
        initEvents();

        geocoder = new GClientGeocoder();
        $("#mapmessagewhere").html("You can use the <strong>'Where?'</strong> search above to help centre the map on a location.");

        updateBounds();

        removeAllMarkers();
    }
}

function initEvents() {
    GEvent.addListener(map, "dragend", mapMoveEnd);
    GEvent.addListener(map, "zoomend", mapZoomEnd);
}

// event handlers

function mapMoveEnd() {
    cropMarkers();
}

function mapZoomEnd(oldZoom, newZoom) {
    if (newZoom > oldZoom) {//zoom in
        cropMarkers();
    } else {
        removeAllMarkers();
    }
}

// reduce Marker Array

function removeAllMarkers() {
    markerArray = [];
    getNewMarkers();
}

function cropMarkers() {
    updateBounds();
    //remove out-of-sight markers 
    var tempArray = []
    for (id in markerArray) {
        if (markerArray[id].latitude > north || markerArray[id].latitude < south || markerArray[id].longitude < west || markerArray[id].longitude > east) {
            // marker is dropped
        } else {
            tempArray.push(markerArray[id]);
        }
    }
    markerArray = tempArray;

    getNewMarkers();
}

function removeTypeMarkers() {
    //remove out-of-sight markers 
    if (type == "yellow" || type == "white") {
        var tempArray = []
        for (id in markerArray) {
            if (markerArray[id].colour != type) {
                // marker is dropped
            } else {
                tempArray.push(markerArray[id]);
            }
        }
        markerArray = tempArray;
    }
    getNewMarkers();
}

function updateBounds() {
    bounds = map.getBounds();
    north = bounds.getNorthEast().lat();
    east = bounds.getNorthEast().lng();
    south = bounds.getSouthWest().lat();
    west = bounds.getSouthWest().lng();
}

// get & build markers

function getNewMarkers() {
    createMarkers()//instant update... the json may take a while
    getNewJSON();
}

function getNewJSON() {
    //alert("getNewJSON");
    $.getJSON("/Search/MapSearchAjax?latitudeNorth=" + north + "&latitudeSouth=" + south + "&longitudeEast=" + east + "&longitudeWest=" + west + "&type=" + type,
        function(data) {
            JSONResults = data;
            updateMarkerArray();
        });
}

function updateMarkerArray() {

    //alert(JSONResults.length);
    for (var i = 0; i < JSONResults.length; i++) {


        if (markerArray.length < markerMax) {

            // need a check for duplicates
            var invalid = "FALSE";

            if (type == "yellow" && JSONResults[i].EntryId.charAt(0) != "Y") {
                invalid = "TRUE";
            } else if (type == "white" && JSONResults[i].EntryId.charAt(0) != "W") {
                invalid = "TRUE";
            }

            if (invalid == "FALSE") {
                for (var j = 0; j < markerArray.length; j++) {
                    if (JSONResults[i].EntryId == markerArray[j].id) {
                        invalid = "TRUE";
                    }
                    if (JSONResults[i].Latitude == markerArray[j].latitude && JSONResults[i].Longitude == markerArray[j].longitude) {
                        invalid = "TRUE";
                    }
                }
            }



            if (invalid == "TRUE") {
                // marker already exists or is not the right type: do not add
            } else {
                // marker does not yet exist: add it
                var colour = 'white';
                if (JSONResults[i].EntryId.charAt(0) == "Y") {
                    colour = 'yellow';
                }
                markerArray.push(
						{
						    'id': JSONResults[i].EntryId,
						    'latitude': JSONResults[i].Latitude,
						    'longitude': JSONResults[i].Longitude,
						    'description': '<div class="result">' + JSONResults[i].DisplayString + "</div>",
						    'colour': colour
						}
					);


            }
        } else {
            i = 10000000;
        }
    }

    createMarkers();
}





// marker creation

function createMarkers() {

    map.clearOverlays();
    latlng = []
    for (id in markerArray) {
        createMarker(markerArray[id])
    }
}

function createMarker(thisMarker) {
    var icon;
    if (thisMarker.colour == 'yellow') {
        icon = yellowIcon;
    } else {
        icon = whiteIcon;
    }

    var center = new GLatLng(thisMarker.latitude, thisMarker.longitude);

    latlng.push(center);
    var marker = new GMarker(center, { icon: icon });
    marker.infoOpen = 0;
    marker.description = thisMarker.description;

    GEvent.addListener(marker, "click", function() {
        if (marker.infoOpen == 0) {
            marker.openInfoWindowHtml(marker.description);
            marker.infoOpen = 1;
        } else {
            marker.closeInfoWindow();
            marker.infoOpen = 0;
        }
    });

    map.addOverlay(marker);
}


// init functions	

function centerView() {
    var latlngbounds = new GLatLngBounds();
    for (var i = 0; i < latlng.length; i++) {
        latlngbounds.extend(latlng[i]);
    }
    map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));
}

function createIcons() {
    whiteIcon = new GIcon(G_DEFAULT_ICON);
    whiteIcon.image = "/Content/images/gmaps/mapmarker-white.png";
    whiteIcon.iconSize = new GSize(24, 29);
    whiteIcon.iconAnchor = new GPoint(12, 29);
    whiteIcon.shadow = "/Content/images/gmaps/mapmarker-shadow.png";
    whiteIcon.shadowSize = new GSize(43, 29);

    yellowIcon = new GIcon(G_DEFAULT_ICON);
    yellowIcon.image = "/Content/images/gmaps/mapmarker-yellow.png";
    yellowIcon.iconSize = new GSize(24, 29);
    yellowIcon.iconAnchor = new GPoint(12, 29);
    yellowIcon.shadow = "/Content/images/gmaps/mapmarker-shadow.png";
    yellowIcon.shadowSize = new GSize(43, 29);
}

$(document).ready(function() {

    $("#googlemapcontainer").css("visibility", "visible");
    $("#googlemapcontainer").css("position", "relative");


    $("#searchbutton").click(function() {
        geolookup($("#queryWhere").val());
    });

    $("#queryWhere").keydown(function(event) {
        if (event.keyCode == 13) {
            geolookup($("#queryWhere").val());
        }
    });


    function whiteYellowFilter() {
        if ($("#whitePagesFilter").attr("checked") && $("#yellowPagesFilter").attr("checked")) {
            type = "";
        } else if (!$("#whitePagesFilter").attr("checked") && $("#yellowPagesFilter").attr("checked")) {
            type = "yellow";
        } else if ($("#whitePagesFilter").attr("checked") && !$("#yellowPagesFilter").attr("checked")) {
            type = "white";
        } else if (!$("#whitePagesFilter").attr("checked") && !$("#yellowPagesFilter").attr("checked")) {
            type = "";
        }
        removeTypeMarkers();
    }

    $("#whitePagesFilter").click(function() {
        if (!$("#whitePagesFilter").attr("checked") && !$("#yellowPagesFilter").attr("checked")) {
            $("#yellowPagesFilter").attr("checked", true)
        }
        return whiteYellowFilter();
    });

    $("#yellowPagesFilter").click(function() {
        if (!$("#whitePagesFilter").attr("checked") && !$("#yellowPagesFilter").attr("checked")) {
            $("#whitePagesFilter").attr("checked", true)
        }
        return whiteYellowFilter();
    });


});
