window.markers = new Array();
window.points = new Array();

function onPopup(e)
{
    var target = getTarget(e);
    var node = document.getElementById(target.properties.targetid);

    cancelEvent(e);

    if (node.value != '') {
        popup(target.properties.targethref,target.properties.targetwidth,target.properties.targetheight,target.properties.targethref,'no','no','no');
    }
    return false;
}

/**
 * Prepares the map
 */
function loadMap()
{
// TODO: maybe include this javascript-file in the same way you include maps.js
    if (document.getElementById('map')) {
        prepareMap('map', 695, 450);
        if (GBrowserIsCompatible()) {
            window.map = new GMap2(document.getElementById('map'), {mapTypes:[G_NORMAL_MAP,G_SATELLITE_MAP, G_HYBRID_MAP]});
            map.addControl(new GMapTypeControl());
            map.addControl(new GLargeMapControl());
            map.setCenter(new GLatLng(18.0737915168,-13.952636719), 1);

            setupMapManager();

            var customView = getFragmentParams();
            if (customView) applyMapView(customView, map);

            showMapLink(document.getElementById('map'), map, getText('LinkToCurrentPage'));
        }
    }
}

function setupMapManager()
{
    window.mapmanager = new GMarkerManager(window.map);

    var markers = [];
    for (var a in window.markers) {
        if (window.markers[a] instanceof GMarker) {
            window.map.addOverlay(window.markers[a]);
        }
    }
}

function getHeaderHTML(href, title, menuTitle)
{
    return '<a href="' + href + '" title="' + title + '">' + menuTitle + '</a>';
}

function getBodyHTML(title, description, thumbnail)
{
    return '<p>' + ((thumbnail != '') ? '<img src="' + thumbnail + '" alt="' + title + '" class="imgbox float-left"/>' : '') + description + '<br class="clear-both"/></p>';
}

function onChangeSelection(e)
{
    if (e) {
        cancelEvent(e);

        var target = getTarget(e);

        if (target) {
            var loc = target.options[target.selectedIndex].value;
            document.location.href = loc;
        }
    }
}

function zoomToDestination(id, marker)
{
    if (marker) {
        marker.opened = false;

        var linktext = (marker.markerType == 'subdestination') ? getText('MapsHotelsAreBeingFetched') : getText('MapsDestinationsAreBeingFetched')

        var text = '<h2 class="markerheader">' + marker.title + '<\/h2>' + '<div class="markerbody">' + linktext + '<\/div>';
        var opts = new Object();
        opts.maxWidth = 400;
        opts.maxHeight = 350;
        marker.openInfoWindowHtml(text, opts);

        // see if it's not already clicked
        if (marker.fetchedChildren) {

            // zoom and pan to destination position
            window.map.setCenter(marker.childrenCenter, marker.childrenZoomlevel);

            // remove currently open info window
            window.map.closeInfoWindow();

            return;
        }
    }

    fetchChildren(id, marker);
}

function fetchChildren(id, marker)
{
    // execute the xmlhttprequest
    AjaxRequest.get(
        {
          'url':'/?action=GetHotels&id='+id,
          'generateUniqueUrl':false,
          'onSuccess':processChildren,
          'marker':marker
        }
    );
}

/**
 *
 */
function processChildren(req)
{
    // initialize variables
    var doc = req.responseXML.documentElement;
    var children = doc.getElementsByTagName('child');
    var marker, child, id, key;
    var markers = [];

    // get parent marker
    var parentMarker = req.parameters.marker;

    var prefix = '';
    if (parentMarker) {
        prefix += parentMarker.prefix;
    }

    if (children && (children.length > 0)) {

        // traverse through children
        for (var i = 0; i < children.length; i++) {

            marker = null;
            child = children.item(i);
            id = child.getAttribute('id');

            if (id) {

                // create new marker for point
                marker = createMarkerFromNode(child, child.getAttribute('markertype'), id, prefix);
                if (marker) {
                    window.markers[id] = marker;
                    markers.push(marker);
                }
            }
        }
    }

    if (markers.length > 0) {

        // calculate boundaries and zoomlevel
        var mapnode = doc.getElementsByTagName('map').item(0);
        var centerPoint = new GLatLng(mapnode.getAttribute('center_x'), mapnode.getAttribute('center_y'))
        var bounds = new GLatLngBounds(new GLatLng(mapnode.getAttribute('bottom'), mapnode.getAttribute('left')), new GLatLng(mapnode.getAttribute('top'), mapnode.getAttribute('right')));
        var zoomlevel = window.map.getBoundsZoomLevel(bounds);

        // make sure zoomlevel does not exceed 12 when we have only 1 marker
        // this prevents excessively zooming
        if ((markers.length < 2) && (zoomlevel > 10)) zoomlevel = 10;

        // add markers to the map manager
        window.mapmanager.addMarkers(markers, zoomlevel);

        // set new center
        window.map.setCenter(centerPoint, zoomlevel);

        // set properties to parent marker
        if (parentMarker) {
            parentMarker.childrenCenter = centerPoint;
            parentMarker.childrenZoomlevel = zoomlevel;
        }

        // refresh the manager to show the new markers
        window.mapmanager.refresh();

        // remove currently open info window
        window.map.closeInfoWindow();

    } else {

        // no markers added found, at least give a warning
        if (parentMarker) {

            var linktext = (parentMarker.markerType == 'subdestination') ? getText('MapsNoHotelsFound') : getText('MapsNoDestinationsFound')
            var href = parentMarker.prefix + ((parentMarker.markerType == 'subdestination') ? 'hotels/' : '');
            var text = '<h2 class="markerheader">' + parentMarker.title + '<\/h2>' + '<div class="markerbody">' + linktext + '<p><a href="' + href + '" class="destination-link" title="' + getText('MapsOpenHotelsLink') + '">' + getText('MapsNoHotelsLink') + '</a></p><\/div>';
            var opts = new Object();
            opts.maxWidth = 300;
            opts.maxHeight = 350;

            GEvent.addListener(parentMarker, "click", function() { parentMarker.openInfoWindowHtml(text, opts); });

            parentMarker.openInfoWindowHtml(text, opts);
        }
    }

    // remember we fetched the children
    if (parentMarker) {
        parentMarker.fetchedChildren = true;
    }
}

function createMarkerFromNode(node, type, id, parentKey)
{
    var marker;

    if (node) {

        // get child properties
        var key          = node.getAttribute('prefix');
        var container_id = getSubNodeValue(node, 'id');
        var loc          = node.getElementsByTagName('location').item(0);
        var title        = getSubNodeValue(node, 'title');
        var menuTitle    = getSubNodeValue(node, 'menutitle');
        var description  = getSubNodeValue(node, 'description');
        var thumbnail    = getSubNodeValue(node, 'thumbnail');


        // make sure location is set
        if (loc) {

            // create new point
            var point = new GLatLng(loc.getAttribute('x'), loc.getAttribute('y'));
            window.points.push(point);

            if (type == 'hotel') {

                var prefix = parentKey + 'hotels/' + key; // add section 'hotels/' for hotels
                var stars = getSubNodeValue(node, 'stars');
                var suffix = getSubNodeValue(node, 'suffix');
                var body = getBodyHTML(title, description, thumbnail);

                marker = createHotelMarker(type, point, prefix, title, menuTitle, body, stars, suffix);

            } else {

                var prefix = parentKey + key;
                var body = getBodyHTML(title, description, thumbnail);

                marker = createDestinationMarker(type, point, prefix, title, menuTitle, body, container_id);
            }
        }
    }

    return marker;
}

/*
 * Creates a marker at the given point with the given text
 * @param GLatLng point The point to use
 * @param string title The marker header title
 * @param string body The body (can contain raw html)
 * @return GMarker The marker
 */
function createHotelMarker(type, point, key, title, menuTitle, body, stars, suffix)
{
    var opts = new Object();
    opts.maxWidth = 400;
    opts.altTitle = title;

    var header = getHeaderHTML(key, title, menuTitle);
    var marker = createChildMarker(point, menuTitle, body, opts);

    var text = '<h2 class="marker-hotelheader">' + header + '<\/h2>';
    text += '<div class="marker-hotelproperties">';

    if (stars > 0) {
        for (var i = 0; i < stars; i++) text += '<img src="/images/star.gif" alt=""/>';
    }

    if (suffix != '') text += '<p class="hotelsuffix">' + suffix + '</p>';

    text += '</div>';
    text += '<div class="markerbody">' + body + '<\/div>';

    // store these variables
    marker.title = title;
    marker.prefix = key;
    marker.markerType = type;

    var opts = new Object();
    opts.maxWidth = 400;
    opts.maxHeight = 350;

    GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(text, opts); });
    return marker;
}

/*
 * Creates a marker at the given point with the given text
 * @param GLatLng point The point to use
 * @param string title The marker header title
 * @param string body The body (can contain raw html)
 * @return GMarker The marker
 */
function createDestinationMarker(type, point, key, title, menuTitle, description, id)
{
    var opts = new Object();
    opts.maxWidth = 400;
    opts.altTitle = title;

    var linktext = (type == 'subdestination') ? getText('MapsHotelsLink') : getText('MapsDestinationsLink')
    var link = '<a href="' + key + '" class="destination-link">' + menuTitle + '</a>';
    var marker = createChildMarker(point, link, description, opts);

    var body = description + '<p><span id="' + 'destinationlink_' + id + '" class="destination-link">' + linktext + '</span></p>'
    var text = '<h2 class="markerheader">' + link + '</h2>' + '<div class="markerbody">' + body + '<\/div>';

    // store these variables
    marker.title = link;
    marker.prefix = key;
    marker.markerType = type;

    var opts = new Object();
    opts.maxWidth = 400;

    GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(text, opts); });
    GEvent.addListener(marker, "infowindowopen", function() {
        if (document.getElementById('destinationlink_' + id)) {
            GEvent.addDomListener(document.getElementById('destinationlink_' + id), 'click', function() { zoomToDestination(id, marker); });
        }
    });
    return marker;
}

addLoadEvent(loadMap);