﻿var map;
var geocoder;
var address;
var searchControl;
var localSearchOptions;
var proxy;
var blueIcon;
var markerIndex;
var MAX_MARKER_COUNT = 20;
var markerArray;
var UPDATE_INTERVAL_SECONDS = 120;
var OVERLAP_DISTANCE_KM = 20;
var SERVICE_URL = "WeatherDataService.svc";
// var SERVICE_URL = "WdsHandler.ashx";
// var SERVICE_URL = "WeatherDataService.svc";
// var SERVICE_URL = "services/WeatherUpdateService.asmx";

function geoCoderInit() {
    geocoder = new GClientGeocoder();
}

function mapSearchInit(map) {
    localSearchOptions = {
        resultList: google.maps.LocalSearch.RESULT_LIST_SUPPRESS,
        searchFormHint: "voer postcode of plaats in",
        onSearchCompleteCallback: setMapSearchResults
    };
    map.addControl(new google.maps.LocalSearch(localSearchOptions),
        new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(1, 1))
    );
}

function setMapSearchResults(searcher) {
    if (searcher && searcher.results && searcher.results.length > 0) {
        var result = searcher.results[0];
        var address;
        if (result.addressLines.length > 1)
            address = result.addressLines[0] + ', ' + result.addressLines[1];
        else
            address = result.title;

        try { window.top.$('#locname')[0].value = address; } catch (err) { }
        try { window.top.$('#address')[0].value = address; } catch (err) { }
        try { window.top.$('#lat')[0].value = result.lat; } catch (err) { }
        try { window.top.$('#lon')[0].value = result.lng; } catch (err) { }
        try { window.top.$('#countryCode')[0].value = result.country; } catch (err) { }
        try { window.top.$('#countryName')[0].value = result.country; } catch (err) { }
        try { window.top.$('#administrativeArea')[0].value = result.region; } catch (err) { }
        try { window.top.$('#localityName')[0].value = result.city; } catch (err) { }
        try { window.top.$('#dependentLocalityName')[0].value = result.city; } catch (err) { }
        try { window.top.$('#thoroughfareName')[0].value = result.addressLines[0]; } catch (err) { }
        try { window.top.$('#postalcode')[0].value = ''; } catch (err) { }
        try { window.top.$('#accuracy')[0].value = result.accuracy; } catch (err) { }
    }
}

function getClientLocation() {
    if (google.loader.ClientLocation) {
        alert(google.loader.ClientLocation.address.region);
    }
}

function initTemperatureMarker() {    
    proxy = new Sys.Data.DataService(SERVICE_URL);
    blueIcon = new GIcon(G_DEFAULT_ICON);
    blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    markerOptions = { icon: blueIcon };
    markerIndex = 10;
    markerArray = [];
}

function initDefaultTemperatureMarkers(clear) {
    $("#image_load").css("visibility", "visible");
    if (blueIcon == null) initTemperatureMarker();
    try {
        if (map == null) return;
        if (clear == true) map.clearOverlays();
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var lngSpan = northEast.lng() - southWest.lng();
        var latSpan = northEast.lat() - southWest.lat();
        if (proxy == null) proxy = new Sys.Data.DataService(SERVICE_URL);
        
        proxy.query("WeatherInBounds?bounds=" + bounds, wal_queryDefaultSuccess, wal_queryFailure);        
    }
    catch (err) { }
}

function addTemperatureMarkers(previousBounds) {
    $("#image_load").css("visibility", "visible");
    if (blueIcon == null) initTemperatureMarker();
    try {
        if (map == null) return;
        var bounds = map.getBounds();
        if (proxy == null) proxy = new Sys.Data.DataService(SERVICE_URL);
        proxy.query("WeatherInBounds?prevbounds=" + previousBounds + "&bounds=" + bounds, wal_queryDefaultSuccess, wal_queryFailure);
    }
    catch (err) { }
    clearTemperatureMarkersOffMap();
}

function addTemperatureMarker() {
    if (blueIcon == null) initTemperatureMarker();
    try {
        if (map == null) return;
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var lngSpan = northEast.lng() - southWest.lng();
        var latSpan = northEast.lat() - southWest.lat();
        if (proxy == null) proxy = new Sys.Data.DataService(SERVICE_URL);
        proxy.query("WeatherInBounds?bounds=" + bounds, wal_querySuccess, wal_queryFailure);
    }
    catch (err) { }
    // setTimeout('addTemperatureMarker()', UPDATE_INTERVAL_SECONDS * 1000);
}

function wal_querySuccess(result, context, operation) {
    if (result && result.length > MAX_MARKER_COUNT && markerIndex > -1) {
        try {
            var point = new GLatLng(result[markerIndex].Latitude, result[markerIndex].Longitude);
            var m = setMarkerDetails(point, result[markerIndex]);
            rollTemperatureMarkers();
            markerArray.unshift(m);
            map.addOverlay(m);
        }
        catch (err) { }
        markerIndex--;
    }
    if (markerIndex < 0) markerIndex = MAX_MARKER_COUNT;
}

function wal_queryDefaultSuccess(result, context, operation) {

    if (result && result.length > 0) {
        try {
            for (index = 0; index < result.length; index++) {
                var point = new GLatLng(result[index].Latitude, result[index].Longitude);
                var m = setMarkerDetails(point, result[index]);
                markerArray.unshift(m);
                map.addOverlay(m);
            }
        }
        catch (err) { }
    }
    $("#image_load").css("visibility", "hidden");
}

function setMarkerDetails(point, details) {
    var localTime = new Date(details.EnteredDateTime);    

    var weatherIcon = new GIcon(G_DEFAULT_ICON);
    weatherIcon.shadow = "";
    weatherIcon.image = "http://www2.buienradar.nl/wicon.php?icon=" + details.WeatherFeelingIcon + "&temp=" + details.Temperature;
    if (details.WeatherFeelingIcon == "0")
        weatherIcon.image = "http://www2.buienradar.nl/wicon.php?icon=" + details.WeatherFeelingIcon + "&temp=" + details.Temperature;
    weatherIcon.iconSize = new GSize(47, 56);
    weatherIcon.infoWindowAnchor = new GPoint(23, 2);
    weatherIcon.imageMap = [0, 0, 47, 0, 47, 56, 0, 56];
    markerOptions = { icon: weatherIcon };

    var m = new GMarker(point, markerOptions);
    m.clickable = true;
    m.draggable = false;
    GEvent.addListener(m, "click", function() {
        var location = details.CityName;
        if (details.postalCode != null)
            location = details.postalCode + ", " + location;
        m.openInfoWindowHtml("<br /><b><a href='station.aspx?id=" + details.LocationId + "&zoom=" + map.getZoom() + "'>" +
            location + "</a></b><br />" +
            "<span style='width:50px;'>Tijd: </span>" + localTime.format("HH:mm") + "<br />" +
            "<span style='width:50px;'>Temperatuur: </span>" + details.Temperature + "<br />" +
            "<span style='width:50px;'>Weer: </span><img src='/wicons/" + details.WeatherFeelingIcon + ".gif' /><br />");
    }
        );
    overrideTemperatureMarker(m);
    return m;
}

function rollTemperatureMarkers() {
    if (markerArray[MAX_MARKER_COUNT - 1] != null) {
        var popMarker = markerArray.pop();
        map.removeOverlay(popMarker);
    }
}

function clearTemperatureMarkersOffMap() {

    var bounds = map.getBounds();
    for (i = 0; i < markerArray.length; i++) {
        var om = markerArray[i];
        var point = om.getPoint();
        if (bounds.contains(point) == false) {
            map.removeOverlay(om);
            try {
                markerArray.splice(markerArray.indexOf(i), 1);
            }
            catch (err) { }
        }
    }
}

function overrideTemperatureMarker(m) {
    if (markerArray[MAX_MARKER_COUNT - 1] != null) {
        for (i = 0; i < markerArray.length; i++) {
            var om = markerArray[i];
            if (om.getLatLng() == m.getLatLng()) {
                map.removeOverlay(om);
                try {
                    markerArray.splice(markerArray.indexOf(i), 1);
                }
                catch (err) { }
            }
            if (om.getLatLng().distanceFrom(m.getLatLng()) < getOverlapDistance()) {
                map.removeOverlay(om);
                try {
                    markerArray.splice(markerArray.indexOf(i), 1);
                }
                catch (err) { }
            }
        }
    }
}

function getOverlapDistance() {
    var zoomLevel = map.getZoom();
    return 500 * (1 / zoomLevel * 1 / zoomLevel) * (OVERLAP_DISTANCE_KM * 5000) * 0.4 / zoomLevel * (4 / zoomLevel);
}

function wal_queryFailure(error, context, opeartion) {
    // alert(error);
    $("#image_load").css("visibility", "hidden");
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}


