﻿/// <reference path="jquery-1.4.2.js"/>
var map;
var currentCode = 'Europe';

// contains the current overlays
var overlays = [];
// contains the preloaded overlays
var preloadOverlays = [];
// contains the centered locations of the different countries
var centerLocations = [];
// contains the bouding boxes of all the countries
var boudingBoxes = [];
// contains the levels of zoom for each country
var zoomList = [];
// contains the instructional overlay
var instructionZoom;


// request to load the api now
function loadMaps() {
    // set the center locations
    centerLocations['AT'] = '47.68757916850813, 15.391845703125';
    zoomList['AT'] = 9;

    centerLocations['BE'] = '50.8250, 4.3506';
    zoomList['BE'] = 9;

    centerLocations['CH'] = '47.17664533468975, 8.54461669921875';
    zoomList['CH'] = 9;

    centerLocations['DE'] = '52.02883848153626, 9.898681640625';
    zoomList['DE'] = 7;

    centerLocations['ES'] = '40.287906612507406, -3.702392578125';
    zoomList['ES'] = 7;

    centerLocations['FR'] = '47.2195681123155, 2.318115234375';
    zoomList['FR'] = 7;

    centerLocations['IT'] = '42.932296019030574, 12.030029296875';
    zoomList['IT'] = 7;

    centerLocations['LU'] = '49.55506184757925, 6.1406707763671875';
    zoomList['LU'] = 9;

    centerLocations['NL'] = '51.767839887322125, 5.09765625';
    zoomList['NL'] = 9;

    centerLocations['UK'] = '52.61639023304538, -1.878662109375';
    zoomList['UK'] = 7;

    centerLocations['Europe'] = '48.04870994288686, 7.0751953125';
    zoomList['Europe'] = 5;

    // load the google maps api
    google.load("maps", "2", { "callback": mapsLoaded });
}

// when api is done loading
function mapsLoaded() {
    preLoad();
    currentCode = 'Europe';
    map = new google.maps.Map2(document.getElementById('map'));
    GEvent.addListener(map, "move", function () {
        checkBounds();
    });
    map.setUIToDefault();
    CenterAndZoom(currentCode, zoomList[currentCode]);
    map.enableScrollWheelZoom();

    //  LoadOverlays();
}

function checkBounds() {
    if (boudingBoxes[currentCode].contains(map.getCenter())) {
        return;
    }

    // not ok, find nearest point and go there
    // get the reference data
    var C = map.getCenter();
    var X = C.lng();
    var Y = C.lat();

    // get the boundingbox data
    var AmaxX = boudingBoxes[currentCode].getNorthEast().lng();
    var AmaxY = boudingBoxes[currentCode].getNorthEast().lat();
    var AminX = boudingBoxes[currentCode].getSouthWest().lng();
    var AminY = boudingBoxes[currentCode].getSouthWest().lat();

    if (X < AminX) { X = AminX; }
    if (X > AmaxX) { X = AmaxX; }
    if (Y < AminY) { Y = AminY; }
    if (Y > AmaxY) { Y = AmaxY; }
    map.setCenter(new GLatLng(Y, X));
}

function CenterAndZoom(centerCode, zoomLevel) {
    map.setCenter(CreateLatLngCenter(centerCode), zoomLevel);
}

function CreateLatLngCenter(centerCode) {
    return new google.maps.LatLng(centerLocations[centerCode].split(",")[0], centerLocations[centerCode].split(",")[1]);
}

function LoadOverlays() {

}

function UpdateClasses(event) {
    var shortName = currentCode + '.' + event.name + '.kmz';
    var layerName = BuildFullOverlayName(shortName);
    var geoXml = preloadOverlays[shortName];

    if (geoXml != undefined) {
        if (event.checked) {
            //add this category to the list for the 'currentCode' country.
            map.addOverlay(geoXml);
            overlays[shortName] = geoXml;
        }
        else {
            // remove this category to the list for the 'currentCode' country.
            delete overlays[shortName];
            map.removeOverlay(geoXml);
        }
    }
}

function UpdateCountriesClick(event) {
    // set default zoom to countryZoom.
    //    var zoom = countryZoom;
    //    if (event == 'Europe') {
    //        zoom = defaultZoom;
    //    }

    if (currentCode != 'Europe') {
        // if not europe, we have to delete the previous layers.
        $('#legendClass :checked').each(function () {
            var shortName = currentCode + '.' + this.name + '.kmz';
            //            var layerName = BuildFullOverlayName(shortName);
            var geoXml = overlays[shortName];
            delete overlays[shortName];
            map.removeOverlay(geoXml);
        });
    } else {
        // currentCode is europe, remove the overlay for the instruction message
        $('#instructionsImg').hide();
    }

    currentCode = event;
    CenterAndZoom(currentCode, zoomList[currentCode]);

    $('#legendClass :checked').each(function () {
        var shortName = currentCode + '.' + this.name + '.kmz';
        //        var layerName = BuildFullOverlayName(shortName);
        //        var geoXml = new GGeoXml(layerName);
        //        map.addOverlay(geoXml);
        //        overlays[shortName] = geoXml;
        var geoXml = preloadOverlays[shortName];
        map.addOverlay(geoXml);
        overlays[shortName] = preloadOverlays[shortName];
    });
}

function UpdateCountries(event) {
    var allCountries = [];
    $('#legendCountries :checked').each(function () {
        allCountries.push(this.name);
    });
    UpdateOverlays();
}

function UpdateEurope(event) {
    $('#legendCountries input').each(
        function () {
            if (this.id != 'Europe') {
                $(this).attr("disabled", event.target.checked);
            }
        }
    );
    UpdateOverlays();
}

function BuildOverlayNames(searchQuery) {
    var currentOverlays = [];
    $(searchQuery).each(function () {
        var country = this;
        if (country.name != 'Europe') {
            $('#legendClass :checked').each(function () {
                currentOverlays.push(country.name + '.' + this.name + '.kmz');
            });
        }
    });
    return currentOverlays;
}

function UpdateOverlays() {
    var searchQuery = '#legendCountries';

    if ($('#Europe:checked').val() == undefined) {
        searchQuery += ' :checked';
    }
    else {
        searchQuery += ' input';
    }
    var currentOverlays = BuildOverlayNames(searchQuery);
    WriteOverlays(currentOverlays);
}

function preLoad() {
    $('#legendCountries :input').each(function () {
        var country = this;
        if (country.name != 'Europe') {
            $('#legendClass :input').each(function () {
                var shortName = country.name + '.' + this.name + '.kmz';
                preloadOverlays[shortName] = new GGeoXml(BuildFullOverlayName(shortName));
            });
        }
    });

    boudingBoxes['AT'] = new GLatLngBounds(new GLatLng(46.387489, 9.54041), new GLatLng(49.01582, 17.179899));
    boudingBoxes['BE'] = new GLatLngBounds(new GLatLng(49.5061, 2.541667), new GLatLng(51.502769, 6.400277));
    boudingBoxes['CH'] = new GLatLngBounds(new GLatLng(45.823879, 5.965833), new GLatLng(47.80637, 10.48861));
    boudingBoxes['DE'] = new GLatLngBounds(new GLatLng(47.281101, 5.869443), new GLatLng(54.9174, 15.03805));
    boudingBoxes['ES'] = new GLatLngBounds(new GLatLng(27.73472, -17.99501), new GLatLng(43.774429, 4.336666));
    boudingBoxes['FR'] = new GLatLngBounds(new GLatLng(41.366379, -4.790556), new GLatLng(51.091099, 9.543055));
    boudingBoxes['IT'] = new GLatLngBounds(new GLatLng(36.650829, 6.620172), new GLatLng(47.090542, 18.51083));
    boudingBoxes['LU'] = new GLatLngBounds(new GLatLng(49.448318, 5.731111), new GLatLng(50.172211, 6.522222));
    boudingBoxes['NL'] = new GLatLngBounds(new GLatLng(50.756069, 3.363889), new GLatLng(53.509299, 7.209444));
    boudingBoxes['UK'] = new GLatLngBounds(new GLatLng(49.955269, -8.164723), new GLatLng(60.6311, 1.7425));
    boudingBoxes['Europe'] = new GLatLngBounds(new GLatLng(27.73472, -17.99501), new GLatLng(60.6311, 18.51083));
}

function BuildFullOverlayName(layerName) {
    return 'http://wereldomroep.be-mobile.be/Source/Countries/' + layerName + '?rand=' + (new Date()).valueOf();
}

function WriteOverlays(currentOverlays) {
    map.clearOverlays();
    $(currentOverlays).each(function () {
        map.addOverlay(new GGeoXml(BuildFullOverlayName(this)));
    });
}

$(document).ready(
    function () {
        // set the tooltip for the speedtrap message
        $('#legendClass #tdSpeedTraps').easyTooltip({
            xOffset: 20,
            yOffset: 30
        });

        // load google maps api, this should be the first statementa
        loadMaps();

        // hide some stuff we currently dont need
        $('#legendCountries input').hide();
        $('#legendCountries #EuropeTD').hide();

        $("#legendCountries td").click(
                function (event) {
                    var selector = '#legendCountries td input[name=' + currentCode + ']';
                    $(selector).parent().removeClass("active2");

                    $(this).addClass("active2");
                    UpdateCountriesClick($(this).find('input')[0].name);
                }
            );

        // this seems to work better than the toggleclass alternative.
        $('#legendCountries td').hover(
                function () {
                    $(this).addClass("active");
                },
                function () {
                    $(this).removeClass("active");
                }
        );

        $('#legendClass td').hover(
                function () {
                    $(this).addClass("pointer");
                },
                function () {
                    $(this).removeClass("pointer");
                }
        );

        $("#legendClass input").change(
                            function (event) {
                                UpdateClasses(event.target);
                            }
                        );

        $('#legendClass td').click(
            function (event) {
                if (!$(event.target).is('input')) {
                      var currentVal = $(this).find('input')[0].checked;
                      $(this).find('input')[0].checked = !currentVal;
                      UpdateClasses($(this).find('input')[0]);
                }
            }
        );

        //            $('#legendClass td input').click(
        //            function () {
        //                UpdateClasses($(this));
        //            }
        //        )

    } // function
);


