
jQuery(document).ready(function() {

    jQuery("table.vergunningen_summary tbody tr").click(function() {
        window.location.href=jQuery(this).find("a").attr("href");
    });
    
     if (typeof locations != 'undefined' && locations.length > 0){
        var name = "googlemaps";
        $("#"+name).show();

        geocoder = new google.maps.Geocoder();

        infowindowLevel = 0;
        bounds = new google.maps.LatLngBounds;
        var options = {
            mapTypeId: google.maps.MapTypeId.HYBRID, // HYBRID, SATELLITE, ROADMAP of TERRAIN
            scrollwheel: false,
            navigationControl: true
        }

        map = new google.maps.Map(
            document.getElementById(name),
            options
            );

        initialize();
     }else{
         $("#googlemaps").hide();
     }

    jQuery("#all-categories").click(function(){
        var checkall=false;
        
        if (jQuery("#all-categories").is(":checked")){
           checkall = true;
        }

        jQuery(".vergunning_category").each(function(){
            if (checkall == true){
                jQuery(this).attr("checked","checked");
                jQuery(".vergunning_table_"+jQuery(this).attr("id")).show();
            }else{
                jQuery(this).removeAttr("checked");
                jQuery(".vergunning_category").each(function(){
                    jQuery(".vergunning_table_"+jQuery(this).attr("id")).hide();
                });
            }

            update_urls(checkall,jQuery(this).val());
        });
        
    });

    jQuery(".vergunning_category").click(function(){
        var checked = false;
        if (jQuery(this).is(":checked")){

            var all_categories_checked = true;

            checked = true;

            jQuery(".vergunning_table_"+jQuery(this).attr("id")).show();

            jQuery(".vergunning_category").each(function(){
               if (!jQuery(this).is(":checked")){
                   all_categories_checked = false;
               }
            });

            if (all_categories_checked == true){
                jQuery("#all-categories").attr("checked","checked");
            }
        }else{
            jQuery(".vergunning_table_"+jQuery(this).attr("id")).hide();
            jQuery("#all-categories").removeAttr("checked");
        }

        update_urls(checked,jQuery(this).val());

    });

    //this function makes sure that all urls are set correctly
    jQuery(".vergunning_category").each(function(){
        var checked = false;
        if (jQuery(this).is(":checked")){
            checked = true;
        }
        update_urls(checked,jQuery(this).val());
    });

    jQuery(".select_year").change(function(){
        //get all weeks of the current year
        jQuery(".select_week").children().remove();
        jQuery.ajax({
            'type': 'GET',
            'url': 'index.php',
            'data': {
                'simaction': 'dynamic_js',
                'toonactie': 'ajax',
                'module':'module_vergunning',
                'yearnr': jQuery(".select_year").val()
            },
            'success': function(weeknumber_string) {
                var aWeeks = weeknumber_string.split(",");
                for(var i=0; i<aWeeks.length; i++){
                    jQuery(".select_week").append('<OPTION value="'+aWeeks[i]+'">'+aWeeks[i]+'</OPTION>');
                }
            }
        });
    });
});

function update_urls(checked,category_id){
    jQuery(".vergunning_table_tr").children().each(function(){
        var href = jQuery(this).children(":first").attr("href");

        if (checked == true){
            href = href+"&category[]="+category_id;
        }else{
            href = href.replace("&category[]="+category_id,"");
        }

        jQuery(this).children(":first").attr("href",href);
    });
}

function initialize() {
    for (var i = 0; i < locations.length; i++) {
        var location = locations[i];
        if((location[1] == undefined && location[2] == undefined) || (location[1] == "" && location[2] == "")) {
            geocode(location[4]+' '+location[5]+' Nederland', location[0], location[3]);
            continue;
        } else {
            var markerLatLon = new google.maps.LatLng(location[1], location[2]);
            var marker = add_marker(markerLatLon, location[0], location[3]);
        }

        if (locations.length > 1) {
            bounds.extend(markerLatLon);
        }
    }

    if (locations.length > 1) {
        map.fitBounds(bounds);
    } else {
        map.setCenter(markerLatLon);
        map.setZoom(15);
    }
}

function attachInfowindow(marker, text) {
    var infowindow = new google.maps.InfoWindow({content:text,maxWidth:100});

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setZIndex(++infowindowLevel);
        infowindow.open(map,marker);
    });
}

function geocode(addr, title, url) {
    //use the geocoder object to translate an address into a latitude and longtitude
    geocoder.geocode({'address': addr}, geocodeResult);
    //callback to be used for the geocoder translation call
    function geocodeResult(response, status) {

        //if the address was successfully translated to a latitude and longtitude
        if (status == google.maps.GeocoderStatus.OK && response[0]) {
            var markerLatLon = response[0].geometry.location;
            var marker = add_marker(markerLatLon, title, url);
        }else{
            mark_address_as_not_map(url);
            return;
        }

        //adjust the map position
        if (locations.length > 1) {
            //there are multiple markers, make sure all markers are visible
            map.fitBounds(bounds);
        } else {
            //there is only one marker, make sure it is centered and adjust the zoom-level
            map.setCenter(markerLatLon);
            map.setZoom(15);
        }
    }
}

function add_marker(latLon, title, url) {
    var marker = new google.maps.Marker({
        position: latLon,
        map: map,
        icon: icon,
        shadow: shadow,
        clickable: true
    });

    if (detail_link_required == false) {
        attachInfowindow(marker, title);
    } else {
        attachInfowindow(marker,title+"<br><a href=\""+url+"\">"+detail_text+"</a>");
    }

    bounds.extend(latLon);
    return marker;
}

function mark_address_as_not_map(url){
    if (jQuery(".vergunningen_note_block").length == 0){
        jQuery(".vergunning_main_container").append(display_note_block());
    }
    
    url = url.substring(url.indexOf("vergunning_id="));
    
    jQuery('td.vergunning_table_tdaddress a[href*="'+url+'"]').each(function(){
        jQuery(this).append('<a href="#vergunningen_note_block" class="vergunningen_note_block"><em class="vergunning_not_available_on_map">*</em></a>');
    });
}

function display_note_block(){
    var html = '<div class="vergunningen_note_block">\n\
                    <a name="vergunningen_note_block" class="vergunningen_note_block_anchor"><em class="vergunning_not_available_on_map">*</em></a> \n\
                    = Vergunning wordt niet op de bovenstaande kaart weergegeven \n\
                </div>';
    return html;
}
