var controls = $A([new GLargeMapControl(), new GMenuMapTypeControl(), new GScaleControl()]);

var data = new Object();
var currentMarkers = $A(new Array());
var map;

function load() {
    data.groups = groups;
    data.locations = locations;

    if (GBrowserIsCompatible()) {
        updateSelectionBox();

        resize();
        Event.observe(window, 'resize', resize);

        var mapDiv = $('map');
        map = new GMap2(mapDiv,
        { mapTypes:  [G_PHYSICAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP]});

        map.clearOverlays();
        map.enableScrollWheelZoom();

        controls.each(function (control) {
            map.addControl(control);
        });
        

        var bounds = new GLatLngBounds(new GLatLng(52.28, 4.72), new GLatLng(52.43, 5.02));
        


        //var coordinate = new GLatLng(52.362578, 4.898773);
        var center = bounds.getCenter();
        map.setCenter(center, 11);
        var zoomLevel = map.getBoundsZoomLevel(bounds);
        map.setZoom(zoomLevel);

        markerManager = new GMarkerManager(map);

        for (var locationId in data.locations) {
            var location = data.locations[locationId];
            if (!location.groupObjects) {
                continue
            }
            if (Object.isUndefined(location.Placemark) || location.Placemark == null || location.Placemark.length == 0) {
                continue;
            }

            var placemark = location.Placemark[0];
            var point = placemark.Point.coordinates;
            if (point.length == 0) {
                continue;
            }

            var locCoordinate = new GLatLng(point[1], point[0]);

            var icon = 'default';
            if(location.icon){
                icon = location.icon;
            }else{
                var icons = location.groupObjects.pluck('icon').uniq();
                if (icons.length == 1) {
                    icon = icons.first();
                }
            }

            var gIcon = new GIcon(G_DEFAULT_ICON);
            gIcon.image = 'images/icons/' + icon + '.png';

            location.marker = new GMarker(locCoordinate, {title: location.name, icon: gIcon});

            var tabs = new Array();

            var locationHtml = '<b>' + location.name + '</b><br />';
            if (location.logo) {
                locationHtml += '<img src="' + location.logo + '" alt="image" />';
            }
            if (location.values) {
                locationHtml += '<table>';
                $A(location.values).each(function(pair) {
                    locationHtml += '<tr><td class="label">' + pair.name + '</td><td>';
                    if (pair.link) {
                        locationHtml += '<a href="' + pair.link + '" target="external">' + pair.value + '</a>';
                    } else {
                        locationHtml += pair.value;
                    }
                    locationHtml += '</td></tr>';
                })
                locationHtml += '</table>';
            }

            tabs.push(new GInfoWindowTab('Locatie', locationHtml));

            if (location.groupObjects && location.groupObjects.length > 0) {
                var groupHtml = '<ul>';
                location.groupObjects.each(function(group) {
                    groupHtml += '<li>';

                    if (group.link) {
                        groupHtml += '<a href="' + group.link + '" target="external">' + group.name + '</a>';
                    } else {
                        groupHtml += group.name;
                    }

                    groupHtml += '</li>'
                });
                groupHtml += '</ul>';

                tabs.push(new GInfoWindowTab('Groepen', groupHtml));
            }

            location.marker.bindInfoWindowTabsHtml(tabs);

            map.addOverlay(location.marker);
            currentMarkers.push(location.marker);
        }
    }
}

function updateSelectionBox() {
    var selectionDiv = $('selection');

    var categoryObjects = new Object();
    var unlistedGroupObjects = new Object();

    var categoryNames = new Array();
    var unlistedGroupNames = new Array();

    for (var name in data.groups) {
        var group = data.groups[name];
        group.visible = true;
        
        $A(group.locations).each(function(locationId) {
            if (data.locations[locationId]) {
                var location = data.locations[locationId];
                if (!location.groupObjects) {
                    location.groupObjects = $A(new Array());
                }
                location.groupObjects.push(group);
            }
        });

        if (group.categories) {
            $A(group.categories).each(function(category) {
                if (categoryObjects[category] == null) {
                    categoryObjects[category] = new Object();
                    categoryObjects[category].name = category;
                    categoryObjects[category].sortedNames = $A([]);
                    categoryObjects[category].groups = new Object();
                    categoryNames.push(category);
                }
                categoryObjects[category].groups[group.id] = group;
                categoryObjects[category].sortedNames.push(group.name);
            })
        } else {
            unlistedGroupObjects[group.id] = group;
            unlistedGroupNames.push(group.name);
        }
    }


    unlistedGroupNames.sort();
    categoryNames.sort();

    data.categories = categoryObjects;
    data.categoryNames = $A(categoryNames);

    data.unlistedGroups = unlistedGroupObjects;
    data.unlistedGroupNames = $A(unlistedGroupNames);

    var groupElementsByGroupName = new Object();

    for (var groupId in data.unlistedGroups) {
        createGroupElement(data.unlistedGroups[groupId], groupElementsByGroupName);
    }

    selectionDiv.update();
    data.unlistedGroupNames.each(function(name) {
        groupElementsByGroupName[name].each(function(groupElement) {
            selectionDiv.appendChild(groupElement);
            selectionDiv.appendChild(new Element('br'));
        })
    });

    data.categoryNames.each(function(name) {
        data.categories[name].sortedNames.sort();
        addCategory(data.categories[name], selectionDiv);
    });
}

function addCategory(category, parentElement) {
    var catHolder = new Element('div');
    catHolder.addClassName('cat');
	$(parentElement.appendChild(catHolder));

    var catElement = new Element('span');
    catElement.addClassName('cat');
    catHolder.appendChild(catElement);
    
    var checkBoxElement = new Element('input', {'type':'checkbox'});	
    checkBoxElement = catElement.appendChild(checkBoxElement);
	checkBoxElement.checked = true;
    category.visible = true;

    var checkBoxLabel = new Element('label', {'for':checkBoxElement.identify()}).update(category.name);
    catElement.appendChild(checkBoxLabel);

    Event.observe(checkBoxElement, 'click', function(category) {
        toggleCategory(this.checked, category);
    }.bind(checkBoxElement, category));

    
    catHolder.appendChild(new Element('br'));

    var groupElementsByGroupName = new Object();

    for (var groupId in category.groups) {
        createGroupElement(category.groups[groupId], groupElementsByGroupName);
    }

    category.sortedNames.each(function(name) {
        groupElementsByGroupName[name].each(function(groupElement) {
            catHolder.appendChild(groupElement);
            catHolder.appendChild(new Element('br'));
        })
    })
}

function createGroupElement(group, groupsByName) {
    var groupElement = new Element('span');
    groupElement.addClassName('group');

    var checkBoxElement = new Element('input', {'type':'checkbox'});
	groupElement.appendChild(checkBoxElement);
	checkBoxElement.checked = true;
    group.visible = true;
    
    if (!group.checkboxes) {
        group.checkboxes = $A(new Array());
    }
    group.checkboxes.push(checkBoxElement);
    Event.observe(checkBoxElement, 'click', function(group) {
        toggleGroup(this.checked, group);
    }.bind(checkBoxElement, group));

    var checkBoxLabel = new Element('label', {'for':checkBoxElement.identify()}).update(group.name);
    groupElement.appendChild(checkBoxLabel);
    if (Object.isUndefined(groupsByName[group.name])) {
        groupsByName[group.name] = $A(new Array());
    }
    groupsByName[group.name].push(groupElement);
}

function toggleGroup(show, group) {
    //alert('group ' + group.name + ": " + show);

    group.visible = show;

    $A(group.locations).each(function(locationId) {
        if (data.locations[locationId]) {
            var location = data.locations[locationId];
            var marker = location.marker;
            if(marker == null || Object.isUndefined(marker)){
                return;
            }
            if (show) {
                map.addOverlay(marker);
                currentMarkers.push(marker);
            } else {
                var visible = false;
                location.groups.each(function(groupId){
                    var group = data.groups[groupId];
                    if(group.visible){
                        visible = true;
                        throw $break;
                    }
                });

                if(!visible){
                    if(marker != null){
                        marker.closeInfoWindow();
                        marker.hide();
                        currentMarkers = currentMarkers.without(marker);
                    }
                }
            }            

            /*location.groupObjects.each(function(group){
                group.checkboxes.each(function(checkbox){
                    checkbox.checked = show;
                })
            })*/
        }
    });

    group.checkboxes.each(function(checkbox){
        checkbox.checked = show;
    });
}

function toggleCategory(show, category) {
    //alert('cat ' + category.name + ": " + show);

    category.visible = show;
    
    for (var groupId in category.groups) {
        var group = category.groups[groupId];
        toggleGroup(show, group);
    }

}

function resize() {
    var contentDiv = $('content');
    var mapDiv = $('map');
    var legendDiv = $('legend');
    var selectionDiv = $('selection');
    mapDiv.style.width = (contentDiv.clientWidth - legendDiv.clientWidth - selectionDiv.clientWidth - 25) + 'px';
    mapDiv.style.height = (contentDiv.clientHeight - 5) + 'px';
}

