﻿var geocoder;
var map;
var markImage = '/_layouts/images/NrkInternet/1043/redcrossmarker.png';
var Regions = new Array();
var markerManager;
var infowindow = new google.maps.InfoWindow();

$().ready(function () {
    //close the menu
    CloseAllSubMenus();

    var googleCanvas = document.getElementById("map_canvas");

    /* The canvas exsisting is also the check for webpart being present on the page */
    if (googleCanvas != null) {
        //create the map and set it to the center of Netherlands
        map = InitializeGoogleMap('52.180669', '5.449219', '7');
        // add a markermanager to the map
        markerManager = new MarkerManager(map);

        /* initialize the javascript object out of the hidden div */
        InitializeRegionsAndLocations();

        // remove the scrollbars by removing 2 overflow auto once the infowindow is ready
        google.maps.event.addListener(infowindow, 'domready', function () {
            $('div.nrkinfowindow').parent().css('overflow', '');
            $('div.nrkinfowindow').parent().parent().css('overflow', '');
        }); 
        
        // when the markermanager is ready, supply it with markers
        google.maps.event.addListener(markerManager, 'loaded', function () {
            // load markers here
            for (var i = 0; i < Regions.length; i++) {
                Regions[i].createmarker(i);

                for (var j = 0; j < Regions[i].locations.length; j++) {
                    Regions[i].locations[j].createmarker(i, j);
                }

            }
            markerManager.refresh();
        });
    }
});

function Region(name, latitude, longitude, zoomlevel, locations) {
    this.name = name;
    this.latitude = latitude;
    this.longitude = longitude;
    this.latlongstored = null;
    this.zoomlevel = zoomlevel;
    this.locations = locations;
}

Region.prototype.latlong = function () {
    if (this.latlongstored == null) {
        this.latlongstored = new google.maps.LatLng(this.latitude, this.longitude);
    }
    return this.latlongstored;
}

Region.prototype.createmarker = function (r) {
    // Create the marker on the map
    var marker = new google.maps.Marker({
        position: this.latlong(),
        title: this.name,
        icon: markImage
    });

    //make click show the region
    google.maps.event.addListener(marker, 'click', function () {
        ShowRegion(r);
        ExpandMenuRegion(r);
    });

    //Make menu trigger corresponding marker.click
    $("ul.nrkRegionsList").children('li').eq(r).children('span').click(function () { google.maps.event.trigger(marker, "click") });

    //add to markermanager responsible for showing correct markers at certain zoomlevel
    markerManager.addMarker(marker, 0, 9);
}

function ShowRegion(r) {
    map.setCenter(Regions[r].latlong());
    map.setZoom(parseInt(Regions[r].zoomlevel));
}

function ShowLocation(r, l) {
    map.setCenter(Regions[r].locations[l].latlong());
    map.setZoom(parseInt(Regions[r].locations[l].adjustedzoomlevel(r)));
}

function Location(name, latitude, longitude, zoomlevel, address, zipcode, city, country, telephonenumber, emailaddress, url) {
    this.name = name;
    this.latitude = latitude;
    this.longitude = longitude;
    this.latlongstored = null;
    this.adjustedzoomlevelstored = null;
    this.zoomlevel = zoomlevel;
    this.address = address;
    this.zipcode = zipcode;
    this.city = city;
    this.country = country;
    this.telephonenumber = telephonenumber;
    this.emailaddress = emailaddress;
    this.url = url;
    this.htmlcontentstringstored = null;
}



Location.prototype.latlong = function () {
    if (this.latlongstored == null) {
        this.latlongstored = new google.maps.LatLng(this.longitude, this.latitude);
    }
    return this.latlongstored;
}

Location.prototype.htmlcontentstring = function () {
    if (this.htmlcontentstringstored == null) {
        var htmlcontentstr = "<div class='nrkinfowindow'>";
        if (this.name != "") { htmlcontentstr += this.name + "<br/>"; }
        if (this.address != "") { htmlcontentstr += this.address + "<br/>"; }
        if (this.zipcode != "") { htmlcontentstr += this.zipcode; }
        htmlcontentstr += (this.city != "") ? " " + this.city + "<br/>" : "<br/>";
        if (this.country != "") { htmlcontentstr += this.country + "<br/>"; }
        if (this.telephonenumber != "") { htmlcontentstr += this.telephonenumber + "<br/>"; }
        if (this.emailaddress != "") { htmlcontentstr += "<a href='mailto:" + this.emailaddress + "'>" + this.emailaddress + "</a><br/>"; }
        if (this.url != "") { htmlcontentstr += "<a href='" + this.url + "' target='_new'>" + this.url + "</a><br/>"; }
     
        htmlcontentstr += "<br/></div>";
        this.htmlcontentstringstored = htmlcontentstr;
    }
    return this.htmlcontentstringstored;
}


// if the zoomlevel of a location is lower than the zoomlevel of the region all the other markers of the region woud become invisible if the user clicks it
// therefore we make sure a locations zoomlevel does not exeed the zoomlevel of the region it is in.
Location.prototype.adjustedzoomlevel = function (r) {
    if (this.adjustedzoomlevelstored == null) {
        this.adjustedzoomlevelstored = (parseInt(this.zoomlevel) < parseInt(Regions[r].zoomlevel)) ? Regions[r].zoomlevel : this.zoomlevel;
    }
    return this.adjustedzoomlevelstored;
}

Location.prototype.createmarker = function (r, l) {

    // Create the marker on the map
    var marker = new google.maps.Marker({
        position: this.latlong(),
        title: this.name,
        icon: markImage
    });

    var contentstring = this.htmlcontentstring();
    //Bind infowindow to marker onclick
    google.maps.event.addListener(marker, 'click', function () {
        ShowLocation(r, l);
        ExpandMenuLocation(r, l);

        infowindow.close(); //hide the infowindow if showing 
        infowindow.setContent(contentstring); //update the content for this marker 

        infowindow.open(map, marker); //open infowindow with new contents on new location
        
    });

    //Make the menu trigger the corresponding marker.click
    $("ul.nrkRegionsList").children('li').eq(r).children('ul.nrkLocationsList').children('li').eq(l).children('span').click(function () { google.maps.event.trigger(marker, "click") });

    //add marker to markgermanager responsible for showing the correct markers at the correct zoomlevel
    markerManager.addMarker(marker, Regions[r].zoomlevel);
}

/*
 *  Set the a google map canvas to a certain latlong center and specified zoomlevel
 *  Zoom defaults to 8 if not set
 */
function InitializeGoogleMap(longitude, latitude, zoomLevel) {
    geocoder = new google.maps.Geocoder();
    var regionLatlng = new google.maps.LatLng(longitude, latitude);
    if (parseInt(zoomLevel) == 0) {
        zoomLevel = 8;
    }
    
    var options = {
        zoom: parseInt(zoomLevel),
        center: regionLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        navigationControl: true
    };
   return new google.maps.Map(document.getElementById("map_canvas"), options);
}

/* 
* looks up regions and locations in the html and creates markers for it on the map
*/
function InitializeRegionsAndLocations() {
    eval($('div.hidden_regionslocation_array').html().toString());
}


function ResetGoogleMap() {
    CloseAllSubMenus();
    var regionLatlng = new google.maps.LatLng('52.180669', '5.449219');
    map.setCenter(regionLatlng);
    map.setZoom(7);
}

/* some menu magic */
function CloseAllSubMenus() {
    infowindow.close();
    $("ul.nrkRegionsList span").removeClass('selected');
    $("ul.nrkRegionsList").children('li').children('img').attr("src", "/_layouts/Images/NrkInternet/1043/nav_arrow_black.png");
    $("ul.nrkRegionsList li ul").removeClass('selected').hide();
}

function ExpandMenuRegion(r) {
    //fold the menu if it was already selected and open, open it if it was selected and previously folded
    if ($("ul.nrkRegionsList").children('li').eq(r).children('span').hasClass('selected')) {
        //Infowindow is possibly opened... close it
        infowindow.close();
        //depending on current visibility adjust menu bullet
        var menubulletsrc = ($("ul.nrkRegionsList").children('li').eq(r).children('img').attr("src") == "/_layouts/Images/NrkInternet/1043/nav_arrow_black.png") ? "/_layouts/Images/NrkInternet/1043/expanded_arrow_black.png" : "/_layouts/Images/NrkInternet/1043/nav_arrow_black.png";

        $("ul.nrkRegionsList").children('li').eq(r).children('img').attr("src", menubulletsrc);
        $("ul.nrkRegionsList").children('li').eq(r).children('ul.nrkLocationsList').first().toggle();
    } else {
        CloseAllSubMenus();
        //get the nth li form the regionslist, add class active to child span / change src of child img / show child ul
        $("ul.nrkRegionsList").children('li').eq(r).children('span').addClass('selected');
        $("ul.nrkRegionsList").children('li').eq(r).children('img').attr("src", "/_layouts/Images/NrkInternet/1043/expanded_arrow_black.png");
        $("ul.nrkRegionsList").children('li').eq(r).children('ul.nrkLocationsList').first().show();
    }
}

function ExpandMenuLocation(r, l) {
    CloseAllSubMenus();
    //get the nth li form the regionslist, add class active to child span
    ExpandMenuRegion(r);
    //get its first nested UL (should only be one) get that ULs nth child (a location li) make it active
    $("ul.nrkRegionsList").children('li').eq(r).children('ul.nrkLocationsList').children('li').eq(l).children('span').addClass('selected');
}
