$(document).ready(
    function(){
        
        var options = { path: '/', expires: 10 };
        
        var dayEventsLimitStart = 0;
        
        // Get the current date
        var currentDate = new Date();
        
        var url = window.location.href;
        var lastChar = url.substring(url.length-1);
        if (lastChar == '/') {
            url = url.substr(0, url.length-1);
        }
        var urlArray = new Array();
        urlArray = url.split('/');
        if (urlArray[urlArray.length-1] != 'agenda') {
            var urlDateParts = urlArray[urlArray.length-1].split('-');
            if (urlDateParts.length == 2) {
                selectedDay = 1;
                selectedMonth = urlDateParts[0];
                selectedYear = urlDateParts[1];
            } else {
                selectedDay = urlDateParts[0];
                selectedMonth = urlDateParts[1];
                selectedYear = urlDateParts[2];
                
                dayEventsLimitStart = 18;
                
                $('.agenda_status').hide();
                formatDate(selectedDay + '_' + selectedMonth + '_' + selectedYear, null, 'agenda_days_events_date');
            }
            $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
        } else {
            if ($.cookie('agendaSelectedDate') == null) {
                $.cookie('agendaSelectedDate', currentDate.getDate() + '_' + (currentDate.getMonth() + 1) + '_' + currentDate.getFullYear(), options);
            } else {
                cookieDate = $.cookie('agendaSelectedDate').split('_');
                if (cookieDate[1] < (currentDate.getMonth() + 1)) {
                    $.cookie('agendaSelectedDate', currentDate.getDate() + '_' + (currentDate.getMonth() + 1) + '_' + currentDate.getFullYear(), options);
                }
            }
            
            var selectedDate = $.cookie('agendaSelectedDate');
            var selectedDateSplit = selectedDate.split('_');
            
            var selectedDay = selectedDateSplit[0];
            var selectedMonth = selectedDateSplit[1];
            var selectedYear = selectedDateSplit[2];
            
            if ($.cookie('agendaDayEvents') == '1') {
                dayEventsLimitStart = 18;
                
                $('.agenda_status').hide();
                formatDate(selectedDay + '_' + selectedMonth + '_' + selectedYear, null, 'agenda_days_events_date');
            }
        }
        
        var currentDay = currentDate.getDate();
        var currentMonth = (currentDate.getMonth() + 1);
        var currentYear = currentDate.getFullYear();
        
        /*
        if (selectedMonth != currentMonth) {
            setMonthBackgrounds(currentMonth + '_' + currentYear, selectedMonth + '_' + selectedYear);
        }*/

        var changingDate = false;

        var dayEvents = false;
        if ($.cookie('agendaDayEvents') == null) {
            $.cookie('agendaDayEvents', '0', options);
            dayEvents = false;
        } else {
            if ($.cookie('agendaDayEvents') == '1') {
                dayEvents = true;
            } else {
                dayEvents = false;
            }
        }
        
        //var dayEventsLimitStart = 0;
        var dayEventsCurrentId = 0;

        var monthLimitStart = 1;
        var monthLimitCount = 14;

        var countries = new Array();
        var types = new Array();
        var cities = new Array();
        
        $('#filter_landen_selected').find('li').each(function() {
             countries.push($(this).find('input[type=checkbox]').val());
        });
        
        if ($.cookie('agendaFilterCountries') != null) {
            countriesSplit = $.cookie('agendaFilterCountries').split('_');
            $(countriesSplit).each(function() {
                if (this != '0') {
                    if (jQuery.inArray(this.toString(), countries) == '-1') {
                        $('input[value=' + this + '][name=filter_landen]').click(filterCountriesInputClick($('input[value=' + this + '][name=filter_landen]').attr('value')));
                    }
                }
            });
        }
        
        if ($.cookie('agendaFilterTypes') != null) {
            typesSplit = $.cookie('agendaFilterTypes').split('_');
            $(typesSplit).each(function() {
                if (this != '0') {
                    $('input[id=type_' + this + '][name=filter_types]').click(filterTypesInputClick($('input[id=type_' + this + '][name=filter_types]').attr('id')));
                }
            });
        }
        
        if ($.cookie('agendaFilterCities') != null) {
            citiesSplit = $.cookie('agendaFilterCities').split('_');
            $(citiesSplit).each(function() {
                if (this != '0') {
                    $('input[value=' + this + '][name=filter_cities]').click(filterCitiesInputClick($('input[value=' + this + '][name=filter_cities]').attr('value')));
                }
            });
        }

        var filterCity = false;
        var filterCountry = false;

        var busy = false;
        
        $.extend($.expr[":"], {  
            "containsNC": function(elem, i, match, array) {  
               return (elem.textContent || elem.innerText || "").toLowerCase  
            ().indexOf((match[3] || "").toLowerCase()) >= 0;  
             }  
        });
        
        jQuery.extend(jQuery.expr[':'], {
            Contains :
                "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0"
        });
        
        filterCountry = true;
        
        $("#agenda_filter_landen").jScrollPane({
            animateTo:true, 
            animateInterval:50, 
            animateStep:3,
            scrollbarWidth: 12,
            scrollbarMargin: 25,
            showArrows: true
        });
        
        $('#agenda_filter_cities_container').hide();

        //$('.agenda_days_container').hide();
        
        $("input[type=checkbox]").checkbox();
        
        $.datepicker.setDefaults(dateLocales);

        // Filter events on event type
        $('input[name=filter_types]').click(filterTypesInputClick);
        
        $('input[name=filter_landen]').click(filterCountriesInputClick);
        
        $('input[name=filter_cities]').click(filterCitiesInputClick);
        
        $('#agenda_google_redirect').submit(function() {
            $('input[name=categories]', this).val(types.join('_'));
            $('input[name=countries]', this).val(countries.join('_'));
            $('input[name=cities]', this).val(cities.join('_'));
            
            return true;
        });
        
        //updateEventCount();
        
        // Datepicker
        $("#datepicker").datepicker({
            defaultDate: new Date(selectedYear,(selectedMonth - 1), selectedDay),
            // If the month of the datepicker changes we have to get new data
            onChangeMonthYear: function(year, month, inst) {
                if (changingDate) {
                    return;
                }
                
                // Retrieve the formatted countries filter string
                var countriesStr = getFilterString(countries);
                // Retrieve the formatted event types filter string
                var typesStr = getFilterStringTypes(types);
                var citiesStr = getFilterString(cities);
                
                // If the newly selected month is the current month we set the selectedDay to the current day
                if (month == currentMonth) {
                    selectedDay = currentDay;
                // Otherwise we'll set the selectedDay to 1
                } //else {
                    //selectedDay = 1;
                //}
                
                // If we are looking at events for a certain day we reload the events for a day with the correct filters
                if (dayEvents) {
                    //getDay(selectedDay, month, year, countriesStr, typesStr, citiesStr);
                // Otherwise we reload the events for a whole month with the given filters.
                } else {
                    //getMonth(selectedDay, month, year, countriesStr, typesStr, citiesStr, selectedDay);
                }
            }
        });
        
        // The event when a month is selected on the top of the agenda.
        $('.agenda_months_item').click(function() {
            // Save the old selected date
            old_date = selectedMonth + '_' + selectedYear;
            
            // Get the new selected date and split it so we can work it
            var date = $(this).attr('id').split('_');
            
            changingDate = true;
            
            dayEvents = false;
            
            // Set the new selected date
            if (date[1] == currentMonth) {
                selectedDay = currentDay;
            } else  {
                selectedDay = 1;
            }
            selectedMonth = date[1];
            selectedYear = date[2];
            
            $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
            
            var countriesStr = getFilterString(countries);
            var typesStr = getFilterStringTypes(types);
            var citiesStr = getFilterString(cities);
            
            // Set the correct backgroud colors
            setMonthBackgrounds(old_date, selectedMonth + '_' + selectedYear);
            if (selectedMonth != currentMonth) {
                $('#datepicker').datepicker('setDate', new Date(selectedYear,(selectedMonth - 1), selectedDay));
                
                getMonth(selectedDay, selectedMonth, selectedYear, countriesStr, typesStr, citiesStr, null)
            } else {
                selectedDay = currentDay;
                $('#datepicker').datepicker('setDate', new Date(selectedYear,(selectedMonth - 1), selectedDay));
                
                getMonth(selectedDay, selectedMonth, selectedYear, countriesStr, typesStr, citiesStr, null);
            }
        });
        
        // This event is called when 'Week > later' is clicked
        $('#agenda_week_right').click(function() {
            // If we are looking at events for a certain day we load the events for the new day with the correct filters
            if (dayEvents) {
                // Save the old date for later use
                old_date = selectedMonth + '_' + selectedYear;
                // We want to go a week further so we add 7 days to the currently selected day.
                selectedDay = (parseInt(selectedDay) + 7);
                
                // Check if the new selectedDay is bigger then the total days in the selected month
                if (selectedDay > daysInMonth(selectedMonth, selectedYear)) {
                    // Set the selectedDay to the first day of the next month
                    selectedDay = 1;
                    selectedMonth = (parseInt(selectedMonth) + 1);
                    changingDate = true;
                    // If the new selectedMonth is bigger then 12 we are going to a new year
                    if (selectedMonth > 12) {
                        selectedMonth = 1;
                        selectedYear = (parseInt(selectedYear) + 1);
                    }
                }
                
                $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
                
                // Set the correct background colors
                setMonthBackgrounds(old_date, selectedMonth + '_' + selectedYear);
                
                // Retrieve the formatted countries filter string
                var countriesStr = getFilterString(countries);
                // Retrieve the formatted event types filter string
                var typesStr = getFilterStringTypes(types);
                var citiesStr = getFilterString(cities);
                
                // Fetch the data for the new selected date
                getDay(selectedDay, selectedMonth, selectedYear, countriesStr, typesStr, citiesStr);
            // Otherwise means that we are still looking at the month overview and we just need to scrollTo to the new date
            } else {
                if (busy) {
                    return false;
                }
                // If the new selectedDay (selectedDay + 7)  is bigger then total days in the selected month minus 7 days then we are at the end of the month
                //if ((parseInt(monthLimitStart) + 7) > (daysInMonth(selectedMonth, selectedYear) + 7)) {
                if ((parseInt(selectedDay) + 7) > (daysInMonth(selectedMonth, selectedYear) - 7)) {
                    busy = true;
                    $('.agenda_small_loader').show();
                    
                    if (selectedMonth == currentMonth) {
                        if (selectedDay != currentDay) {
                            // Reset the background of the currently selected date
                            $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                        }
                    } else {
                        $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                    }
                    
                    // We set the new date so that the last week of the month will be show                    
                    if ((parseInt(selectedDay) + 7) > (daysInMonth(selectedMonth, selectedYear) - 6)) {
                        new_date = (daysInMonth(selectedMonth, selectedYear)-6) + '_' + selectedMonth + '_' + selectedYear;
                        selectedDay = (daysInMonth(selectedMonth, selectedYear)-6);
                    } else {
                        new_date = (parseInt(selectedDay) + 7) + '_' + selectedMonth + '_' + selectedYear;
                        selectedDay = (parseInt(selectedDay) + 7);
                    }
                    // Set the correctly formatted new date
                    formatDate(new_date, 7, 'agenda_status');
                    $.cookie('agendaSelectedDate', new_date, options);
                    
                    // 14_10_2009_head
                    $('#' + new_date + '_head').css('background-color', '#CFEBFF');
                    
                    // Set the new selected day
                    //selectedDay = (daysInMonth(selectedMonth, selectedYear)-6);
                    // Scroll To the correct date
                    $("#agenda_scroll").scrollTo($("#" + new_date), 2000, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});
                // If we are not at the end of the month
                } else {
                    busy = true;
                    $('.agenda_small_loader').show();
                    // New date is old selected days plus 7 days
                    new_date = (parseInt(selectedDay) + 7) + '_' + selectedMonth + '_' + selectedYear;
                    // Set the correctly formatted new date
                    formatDate(new_date, 7, 'agenda_status');
                    
                    if (selectedMonth == currentMonth) {
                        if (selectedDay != currentDay) {
                            // Reset the background of the currently selected date
                            $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                        }
                    } else {
                        $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                    }
                    
                    // Set the new selected day
                    selectedDay = (parseInt(selectedDay) + 7);
                    $.cookie('agendaSelectedDate', new_date, options);
                    
                    $('#' + new_date + '_head').css('background-color', '#CFEBFF');
                    
                    $("#agenda_scroll").scrollTo($("#" + new_date), 2000, {
                        onAfter:function() {
                            // Check if we can still load more days for the current month
                            if ($('#agenda_scroll').attr('scrollWidth') != (102 * daysInMonth(selectedMonth, selectedYear))) {
                                loadMoreDaysInMonth(7);
                            } else {
                                busy = false;
                                $('.agenda_small_loader').hide();
                            }
                        }
                    });
                    
                }
                $('#datepicker').datepicker('setDate', new Date(selectedYear,(selectedMonth - 1), selectedDay));
            }
        });
        
        $('#agenda_week_left').click(function() {
            if (dayEvents) {
                old_date = selectedMonth + '_' + selectedYear;
                selectedDay = (parseInt(selectedDay) - 7);
                if (selectedDay < 1) {
                    selectedMonth = (parseInt(selectedMonth) - 1);
                    changingDate = true;
                    if (selectedMonth < 1) {
                        selectedMonth = 12;
                        selectedYear = (parseInt(selectedYear) - 1);
                    }
                    selectedDay = daysInMonth(selectedMonth, selectedYear);
                }
                
                setMonthBackgrounds(old_date, selectedMonth + '_' + selectedYear);
                $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
                
                var countriesStr = getFilterString(countries);
                var typesStr = getFilterStringTypes(types);
                var citiesStr = getFilterString(cities);
                
                getDay(selectedDay, selectedMonth, selectedYear, countriesStr, typesStr, citiesStr);
                
            } else {
                if (busy) {
                    return false;
                }
                var newSelectedDay = (selectedDay - 7);
                
                if (newSelectedDay >= 1) {
                    if (selectedMonth == currentMonth) {
                        if (newSelectedDay > currentDay) {
                            busy = true;
                            $('.agenda_small_loader').show();
                            new_date = (selectedDay - 7) + '_' + selectedMonth + '_' + selectedYear;
                            // Reset the background of the currently selected date #C4C4C4
                            $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                            // Set the background of the new date if it's not the current day of the month
                            $('#' + new_date + '_head').css('background-color', '#CFEBFF');
                            
                            formatDate(new_date, 7, 'agenda_status');
                            selectedDay = (selectedDay - 7);
                            $("#agenda_scroll").scrollTo($('#' + newSelectedDay + '_' + selectedMonth + '_' + selectedYear), 2000, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});
                        } else if (newSelectedDay <= currentDay) {
                            busy = true;
                            $('.agenda_small_loader').show();
                            // Reset the background of the currently selected date #C4C4C4
                            $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                            
                            selectedDay = currentDay;
                            new_date = selectedDay + '_' + selectedMonth + '_' + selectedYear;
                            formatDate(new_date, 7, 'agenda_status');
                            $("#agenda_scroll").scrollTo($('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear), 2000, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});
                        }
                    } else {
                        busy = true;
                        $('.agenda_small_loader').show();
                        new_date = (selectedDay - 7) + '_' + selectedMonth + '_' + selectedYear;
                        // Reset the background of the currently selected date #C4C4C4
                        $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                        // Set the background of the new date if it's not the current day of the month
                        $('#' + new_date + '_head').css('background-color', '#CFEBFF');
                            
                        formatDate(new_date, 7, 'agenda_status');
                        selectedDay = (selectedDay - 7);
                        $("#agenda_scroll").scrollTo($('#' + newSelectedDay + '_' + selectedMonth + '_' + selectedYear), 2000, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});
                    }
                } else {
                    new_date = 1 + '_' + selectedMonth + '_' + selectedYear;
                    // Reset the background of the currently selected date #C4C4C4
                    $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                    // Set the background of the new date if it's not the current day of the month
                    $('#' + new_date + '_head').css('background-color', '#CFEBFF');
                    
                    formatDate(new_date, 7, 'agenda_status');
                    selectedDay = 1;
                    $("#agenda_scroll").scrollTo($('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear), 2000, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});    
                }
                $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
                $('#datepicker').datepicker('setDate', new Date(selectedYear,(selectedMonth - 1), selectedDay));
            }
        });
        
        $("#agenda_day_right").click(function() {
            if (dayEvents) {
                old_date = selectedMonth + '_' + selectedYear;
                selectedDay = (parseInt(selectedDay) + 1);
                if (selectedDay > daysInMonth(selectedMonth, selectedYear)) {
                    selectedDay = 1;
                    selectedMonth = (parseInt(selectedMonth) + 1);
                    if (selectedMonth > 12) {
                        selectedMonth = 1;
                        selectedYear = (parseInt(selectedYear) + 1);
                    }
                }
                
                setMonthBackgrounds(old_date, selectedMonth + '_' + selectedYear);
                
                $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
                
                changingDate = true;
                
                var countriesStr = getFilterString(countries);
                var typesStr = getFilterStringTypes(types);
                var citiesStr = getFilterString(cities);
                
                getDay(selectedDay, selectedMonth, selectedYear, countriesStr, typesStr, citiesStr);
            } else {
                if (busy) {
                    return false;
                }
                if ((parseInt(selectedDay) + 1) > daysInMonth(selectedMonth, selectedYear) - 6) {
                    busy = true;
                    $('.agenda_small_loader').show();
                    new_date = (daysInMonth(selectedMonth, selectedYear) - 6) + '_' + selectedMonth + '_' + selectedYear;
                    formatDate(new_date, 7, 'agenda_status');
                    $("#agenda_scroll").scrollTo($("#" + new_date), 500, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});
                } else {
                    busy = true;
                    $('.agenda_small_loader').show();
                    new_date = (parseInt(selectedDay) + 1) + '_' + selectedMonth + '_' + selectedYear;
                    if (selectedMonth == currentMonth) {
                        if (selectedDay != currentDay) {
                            // Reset the background of the currently selected date #C4C4C4
                            $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                        }
                    } else {
                        $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                    }
                    // Set the background of the new date if it's not the current day of the month
                    $('#' + new_date + '_head').css('background-color', '#CFEBFF');
                    formatDate(new_date, 1, 'agenda_status');
                    selectedDay = (parseInt(selectedDay) + 1);
                    $("#agenda_scroll").scrollTo($("#" + new_date), 500, {
                        onAfter:function() {
                            if (selectedMonth == currentMonth) {
                                if ($('#agenda_scroll').attr('scrollWidth') != (102 * (daysInMonth(selectedMonth, selectedYear) - (currentDay - 1)))) {
                                    loadMoreDaysInMonth(1);
                                    busy = false;
                                }
                            } else {
                                if ($('#agenda_scroll').attr('scrollWidth') != (102 * daysInMonth(selectedMonth, selectedYear))) {
                                    loadMoreDaysInMonth(1);
                                    busy = false;
                                }
                            }
                            busy = false;
                            $('.agenda_small_loader').hide();
                        }
                    });
                }
                $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
                $('#datepicker').datepicker('setDate', new Date(selectedYear,(selectedMonth - 1), selectedDay));
            }
        });
        
        $('#agenda_day_left').click(function() {
            if (dayEvents) {
                old_date = selectedMonth + '_' + selectedYear;
                selectedDay = (parseInt(selectedDay) - 1);
                if (selectedDay < 1) {
                    selectedMonth = (parseInt(selectedMonth) - 1);
                    selectedDay = daysInMonth(selectedMonth, selectedYear);
                }
                
                setMonthBackgrounds(old_date, selectedMonth + '_' + selectedYear);
                
                $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
                
                var countriesStr = getFilterString(countries);
                var typesStr = getFilterStringTypes(types);
                var citiesStr = getFilterString(cities);
                
                getDay(selectedDay, selectedMonth, selectedYear, countriesStr, typesStr, citiesStr);
            } else {
                if (busy) {
                    return false;
                }
                var newSelectedDay = (selectedDay - 1);
                
                if (newSelectedDay >= 1) {
                    if (selectedMonth == currentMonth) {
                        if (newSelectedDay > currentDay) {
                            $('.agenda_small_loader').show();
                            busy = true;
                            new_date = (selectedDay - 1) + '_' + selectedMonth + '_' + selectedYear;
                            // Reset the background of the currently selected date #C4C4C4
                            $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                            // Set the background of the new date if it's not the current day of the month
                            $('#' + new_date + '_head').css('background-color', '#CFEBFF');
                            formatDate(new_date, 7, 'agenda_status');
                            selectedDay = (selectedDay - 1);
                            $("#agenda_scroll").scrollTo($('#' + newSelectedDay + '_' + selectedMonth + '_' + selectedYear), 500, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});
                        } else if (newSelectedDay == currentDay) {
                            $('.agenda_small_loader').show();
                            busy = true;
                            new_date = currentDay + '_' + selectedMonth + '_' + selectedYear;
                            // Reset the background of the currently selected date #C4C4C4
                            $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                            
                            formatDate(new_date, 7, 'agenda_status');
                            selectedDay = currentDay;
                            $("#agenda_scroll").scrollTo($('#' + newSelectedDay + '_' + selectedMonth + '_' + selectedYear), 500, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});
                        }
                    } else {
                        $('.agenda_small_loader').show();
                        busy = true;
                        new_date = (selectedDay - 1) + '_' + selectedMonth + '_' + selectedYear;
                        // Reset the background of the currently selected date #C4C4C4
                        $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#C4C4C4');
                        // Set the background of the new date if it's not the current day of the month
                        $('#' + new_date + '_head').css('background-color', '#CFEBFF');
                        formatDate(new_date, 7, 'agenda_status');
                        selectedDay = (selectedDay - 1);
                        $("#agenda_scroll").scrollTo($('#' + newSelectedDay + '_' + selectedMonth + '_' + selectedYear), 500, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});
                    }
                }
                $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
                $('#datepicker').datepicker('setDate', new Date(selectedYear,(selectedMonth -1),selectedDay));
            }
        });
        
        $('#agenda_days_dag').click(function() {
             var countriesStr = getFilterString(countries);
             var typesStr = getFilterStringTypes(types);
             var citiesStr = getFilterString(cities);
             
             $('.agenda_status').hide();
            
             getDay(selectedDay, selectedMonth, selectedYear, countriesStr, typesStr, citiesStr);
        });
        
        $('#agenda_days_week').click(function() {
            if (dayEvents) {
                dayEvents = false;
                
                var countriesStr = getFilterString(countries);
                var typesStr = getFilterStringTypes(types);
                var citiesStr = getFilterString(cities);
                
                getMonth(selectedDay, selectedMonth, selectedYear, countriesStr, typesStr, citiesStr, selectedDay);
            } 
        });
        
        $('.agenda_dag_footer').livequery('click', function() {
            
            var date = $(this).attr('id').split('_');
            
            var countriesStr = getFilterString(countries);
            var typesStr = getFilterStringTypes(types);
            var citiesStr = getFilterString(cities);
            
            $('.agenda_status').hide();
            
            getDay(date[0], date[1], date[2], countriesStr, typesStr, citiesStr);
        });
        
        $('.agenda_dag_head').livequery('click', function() {
            var date = $(this).attr('id').split('_');
            
            var countriesStr = getFilterString(countries);
            var typesStr = getFilterStringTypes(types);
            var citiesStr = getFilterString(cities);
            
            $('.agenda_status').hide();
            
            getDay(date[0], date[1], date[2], countriesStr, typesStr, citiesStr);
        });
        
        $('.agenda_events_scroll_right').livequery('click', function() {
            if (busy) {
                return false;
            }
            var lastColumn = $(".agenda_dag_events > :last").attr('id').split('_');
            var lastColumnId = lastColumn[2];
            
            var totalEvents = parseInt($('.agenda_events_dag_total').html());
            
            var maxColumn = null;
            var restWaarde = (totalEvents % 3);
            if (restWaarde == 0) {
                maxColumn = (((totalEvents / 3) * 3) - 3);
            } else {
                maxColumn = (((((totalEvents - restWaarde) / 3) + 1) * 3) - 3);
            }

            busy = true;
            
            if ((dayEventsCurrentId + 9) >= maxColumn) {
                dayEventsCurrentId = (maxColumn - 6);
                $(".agenda_events_dag_start").html((dayEventsCurrentId + 1));
                $(".agenda_events_dag_end").html(totalEvents);
            } else {
                if ((maxColumn - (dayEventsCurrentId + 9)) < 9) {
                    //dayEventsCurrentId = maxColumn - (maxColumn - (dayEventsCurrentId + 9));
                    dayEventsCurrentId = (maxColumn - 6);
                    $(".agenda_events_dag_start").html((dayEventsCurrentId + 1));
                    $(".agenda_events_dag_end").html((parseInt(totalEvents)));
                } else {
                    dayEventsCurrentId = (dayEventsCurrentId + 9);
                    $(".agenda_events_dag_start").html((dayEventsCurrentId + 1));
                    $(".agenda_events_dag_end").html((dayEventsCurrentId + 9));
                }
            }
            $("#agenda_scroll").scrollTo($('#event_column_' + dayEventsCurrentId), 2000, {onAfter: function() {
                if (lastColumnId != maxColumn) {
                    loadMoreDayEvents();
                } else {
                    busy = false; 
                }
            }});
        });
        
        $(".agenda_events_scroll_left").livequery('click', function() {
            if (busy) {
                return false;
            }
            if ((dayEventsCurrentId - 9) >= 0) {
                busy = true;
                dayEventsCurrentId = (dayEventsCurrentId - 9);
                $("#agenda_scroll").scrollTo($('#event_column_' + dayEventsCurrentId), 2000, {onAfter: function() {busy = false;}});
                $(".agenda_events_dag_start").html((dayEventsCurrentId + 1));
                $(".agenda_events_dag_end").html((dayEventsCurrentId + 9));
            } else {
                busy = true;
                dayEventsCurrentId = 0;
                $("#agenda_scroll").scrollTo($('#event_column_' + dayEventsCurrentId), 2000, {onAfter: function() {busy = false;}});
                $(".agenda_events_dag_start").html((dayEventsCurrentId + 1));
                if ((dayEventsCurrentId + 9) > parseInt($('.agenda_events_dag_total').html())) {
                    $(".agenda_events_dag_end").html(parseInt($('.agenda_events_dag_total').html()));
                } else {
                    $(".agenda_events_dag_end").html((dayEventsCurrentId + 9));
                }
            }
        });
        
        $('input[name=filter_landen_search]').keyup(function() {
            if($(this).attr('value') != ''){
                $('#filter_landen').find('li:not(:containsNC(' + $(this).val() + '))').each(function() {
                    $(this).css('display', 'none');
                });
                $('#filter_landen').find('li:containsNC(' + $(this).val() + ')').each(function() {
                    $(this).css('display', 'block');
                });
            } else {
                $('#filter_landen').find('li').each(function() {
                    $(this).css('display', 'block');
                });
            }
            
            if ((parseInt($('#filter_landen').attr('offsetHeight')) + parseInt($('#filter_landen_selected').attr('offsetHeight'))) > 120) {
                $('#agenda_filter_landen_list').css('height', (parseInt($('#filter_landen').attr('offsetHeight')) + parseInt($('#filter_landen_selected').attr('offsetHeight')) + 20) + 'px');
            } else {
                $('#agenda_filter_landen_list').css('height', '80px');
            }
            
            $("#agenda_filter_landen").jScrollPane({
                animateTo:true, 
                animateInterval:50, 
                animateStep:3,
                scrollbarWidth: 12,
                scrollbarMargin: 25,
                showArrows: true
            });
        });
        
        $('.agenda_filter_countries_select').click(function() {
            if (filterCity) {
                filterCity = false;
                $('#agenda_filter_cities_container').hide();
            }
            if ($('#agenda_filter_landen_container').css('display') == 'block') {
                filterCountry = false
                $('#agenda_filter_landen_container').hide();
            } else {
                filterCountry = true;
                $('#agenda_filter_landen_container').show();
            }
        });
        
        $('input[name=filter_cities_search]').keyup(function() {
            if($('input[name=filter_cities_search]').attr('value').length > 0){
                $('#filter_cities').find('li:not(:containsNC(' + $('input[name=filter_cities_search]').val() + '))').each(function() {
                    $(this).css('display', 'none');
                });
                $('#filter_cities').find('li:containsNC(' + $('input[name=filter_cities_search]').val() + ')').each(function() {
                    $(this).css('display', 'block');
                });
            } else {
                $('#filter_cities').find('li').each(function() {
                    $(this).css('display', 'block');
                });
            }
            
            if ((parseInt($('#filter_cities').attr('offsetHeight')) + parseInt($('#filter_cities_selected').attr('offsetHeight'))) > 120) {
                $('#agenda_filter_cities_list').css('height', (parseInt($('#filter_cities').attr('offsetHeight')) + parseInt($('#filter_cities_selected').attr('offsetHeight')) + 20) + 'px');
            } else {
                $('#agenda_filter_cities_list').css('height', '80px');
            }
            
            $("#agenda_filter_cities").jScrollPane({
                animateTo:true, 
                animateInterval:50, 
                animateStep:3,
                scrollbarWidth: 12,
                scrollbarMargin: 25,
                showArrows: true
            });
        });
        
        $('.agenda_filter_cities_select').click(function() {
            if (filterCountry) {
                filterCountry = false;
                $('#agenda_filter_landen_container').hide();
            }
            if ($('#agenda_filter_cities_container').css('display') == 'block') {
                filterCity = false;
                $('#agenda_filter_cities_container').hide();
            } else {
                filterCity = true;
                $('#agenda_filter_cities_container').show();
                $("#agenda_filter_cities").jScrollPane({
                    animateTo:true,
                    animateInterval:50,
                    animateStep:3,
                    scrollbarWidth: 12,
                    scrollbarMargin: 25,
                    showArrows: true
                });
            }
        });
        
        $('#agenda_filter_submit').click(function() {
            var countriesStr = getFilterString(countries);
            var newTypes = new Array();
            jQuery.each(types, function() {
                var type = this.split('_');
                newTypes.push(type[1]);
            })
            var typesStr = getFilterString(newTypes);
            var citiesStr = getFilterString(cities);
            
            $.cookie('agendaFilterCountries', countriesStr, options);
            $.cookie('agendaFilterTypes', typesStr, options);
            $.cookie('agendaFilterCities', citiesStr, options);
            
            //alert($('#datepicker').datepicker('getDate'));
            dateString = $.datepicker.formatDate("dd_mm_yy", $("#datepicker").datepicker("getDate"));
            date = dateString.split('_');
            
            updateEventCount();
            
            if (dayEvents) {
                getDay(date[0], date[1], date[2], countriesStr, typesStr, citiesStr);
            } else {
                getMonth(date[0], date[1], date[2], countriesStr, typesStr, citiesStr, date[0]);
            }
        });

        $('#agenda_ical_dialog').dialog({
            modal: true,
            overlay: {
                opacity: 1,
                background: "black"
            },
            autoOpen: false,
            title: 'iCal url',
            width: 600,
            resizable: false,
            draggable: false
        });
        
        
        $('#agenda_ical_url_show').click(function() {
            $.post(rootUrl + 'ical/generate',
                {
                    'categories': getFilterStringTypes(types),
                    'countries[]': countries,
                    'cities[]': cities
                },
                function(data) {
                    $('#agenda_ical_url').attr('href', rootUrl + 'ical/calendar/' + data);
                    $('#agenda_ical_url').html(rootUrl + 'ical/calendar/' + data);
                    $('#agenda_add_to_google_a').attr('href', 'http://www.google.com/calendar/render?cid=' + rootUrl + '/ical/calendar/' + data + '/calendar.ics');
                    $('#agenda_ical_dialog').dialog('open');
                }
            );
        });
        
        function getMonth(dayNumber, monthNumber, yearNumber, countries, types, cities, days)
        {
            if (monthNumber != currentMonth) {
                monthLimitStart = 1;
            } else {
                monthLimitStart = currentDay;
            }
            
            old_date = selectedMonth + '_' + selectedYear;
            
            if (days != null) {
                if ((parseInt(selectedDay)) > (daysInMonth(selectedMonth, selectedYear) - 6)) {
                    selectedDay = (daysInMonth(selectedMonth, selectedYear)-6);
                } else {
                    selectedDay = days;
                }
            } else {
                if (monthNumber == currentMonth) {
                    selectedDay = currentDay;
                } else {
                    if ((parseInt(selectedDay) + 7) > (daysInMonth(selectedMonth, selectedYear) - 6)) {
                        selectedDay = (daysInMonth(selectedMonth, selectedYear)-6);
                    } else {
                        selectedDay = dayNumber;
                    }
                }
            }
            selectedMonth = monthNumber;
            selectedYear = yearNumber;
            
            if (selectedMonth > 12) {
                selectedMonth = 1;
                selectedYear = (yearNumber + 1);
            } else if (selectedMonth < 1) {
                selectedMonth = 12;
                selectedYear = (selectedYear - 1);
            }
            
            // Unset the background-color for the currently selected month
            setMonthBackgrounds(old_date, selectedMonth + '_' + selectedYear);
            
            $('.agenda_status').show();
            
            $.cookie('agendaDayEvents', '0', options);
            dayEvents = false;
            
            showDayEventsHeader();
            dayEventsLimitStart = 0;
            
            showLoadingBar();
            
            //updateEventCount();
            
            var scrollTo = false;
            if (days != null) {
                if (selectedMonth == currentMonth) {
                    daysCount = ((daysInMonth(selectedMonth, selectedYear) - currentDay) + 1);
                } else {
                    daysCount = daysInMonth(selectedMonth, selectedYear);
                }
                scrollTo = true;
            } else {
                daysCount = monthLimitCount;
            }
            
            formatDate(selectedDay + '_' + selectedMonth + '_' + selectedYear, 1, 'agenda_status');
            
            $.post(rootUrl + 'agenda/month/',
                {
                    'monthnumber': selectedMonth,
                    'yearnumber': selectedYear,
                    'limitstart': monthLimitStart,
                    'limitcount': daysCount,
                    'more': '0',
                    'countries': countries,
                    'types': types,
                    'cities': cities
                },
                function(data) {
                    $('.agenda_head_container').html(data);
                    if (selectedMonth == currentMonth) {
                        monthLimitStart = ((currentDay - 1) + daysCount);
                    } else {
                        monthLimitStart = daysCount;
                    }
                    if (selectedMonth == currentMonth) {
                        if (selectedDay != currentDay) {
                            $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#CFEBFF');
                        }
                    } else {
                         $('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear + '_head').css('background-color', '#CFEBFF');
                    }
                    
                    if (scrollTo) {
                        $("#agenda_scroll").scrollTo($('#' + selectedDay + '_' + selectedMonth + '_' + selectedYear), 2000, {onAfter:function() {busy = false; $('.agenda_small_loader').hide();}});
                    }
                    $('#datepicker').datepicker('setDate', new Date(selectedYear,(selectedMonth - 1), selectedDay));
                }
            );
        }
        
        function getDay(dayNumber, monthNumber, yearNumber, countries, types, cities)
        {
            selectedDay = dayNumber;
            selectedMonth = monthNumber;
            selectedYear = yearNumber;
            
            $.cookie('agendaSelectedDate', selectedDay + '_' + selectedMonth + '_' + selectedYear, options);
            
            //formatDate(selectedDay + '_' + selectedMonth + '_' + selectedYear, null, 'agenda_status');
            
            showLoadingBar();
            
            $.cookie('agendaDayEvents', '1', options);
            dayEvents = true;
            
            dayEventsLimitStart = 0;
            dayEventsCurrentId = 0;
            
            //updateEventCount();
            
            $('.agenda_status').hide();
            
            $.post(rootUrl + 'agenda/day/',
                {
                    'daynumber': selectedDay,
                    'monthnumber': selectedMonth,
                    'yearnumber': selectedYear,
                    'limitstart': dayEventsLimitStart,
                    'limitcount': '18',
                    'more': '0',
                    'countries': countries,
                    'types': types,
                    'cities': cities
                },
                function(data) {
                    var columns = data.match(/agenda_dag_events_column/g);
                    if (columns != null) {
                        columnCount = columns.length;
                    } else {
                        columnCount = 0;
                    }
                    $('.agenda_head_container').html(data);
                    
                    $('.agenda_dag_events').css('width', ((238 * columnCount)) + 'px');
                    
                    $('.agenda_dag_events_footer_container').show();
                    showDayEventsHeader();
                    dayEventsLimitStart = 18;
                    
                    new_date = (selectedDay) + '_' + selectedMonth + '_' + selectedYear;
                    //formatDate(new_date, null, 'agenda_status');
                    formatDate(new_date, null, 'agenda_days_events_date');
                    
                    $('#datepicker').datepicker('setDate',new Date(selectedYear,(selectedMonth -1),selectedDay));
                }
            );
        }
        
        function updateEventCount()
        {
            var countriesStr = getFilterString(countries);
            var typesStr = getFilterStringTypes(types);
            var citiesStr = getFilterString(cities);
            
            $.post(rootUrl + 'agenda/count-month-events/',
                {
                    'daynumber': currentDay,
                    'monthnumber': currentMonth,
                    'yearnumber': currentYear,
                    'countries': countriesStr,
                    'types': typesStr,
                    'cities': citiesStr
                },
                function(data) {
                    events = data.split('_');

                    $('.agenda_months_item').each(function(index) {
                        $('.agenda_month_events_count', $(this)).html(events[index]);
                    });
                }
            );
        }
        
        function setMonthBackgrounds(old_date, new_date)
        {
            $('#month_' + old_date).css('background-color', '#C4C4C4');
                    
            $('#month_' + new_date).css('background-color', 'rgb(93, 93, 93)');
        }
        
        function showDayEventsHeader() {
            if (dayEvents == true) {
                $('.agenda_days_container').show();
            } else {
                $('.agenda_days_container').hide();
            }
        }
        
        function loadMoreDayEvents()
        {
            var countriesStr = getFilterString(countries);
            var typesStr = getFilterStringTypes(types);
            var citiesStr = getFilterString(cities);
            
            $.post(rootUrl + 'agenda/day',
                {
                    'daynumber': selectedDay,
                    'monthnumber': selectedMonth,
                    'yearnumber': selectedYear,
                    'limitstart': dayEventsLimitStart,
                    'limitcount': '9',
                    'more': '1',
                    'countries': countriesStr,
                    'types': typesStr,
                    'cities': citiesStr
                }, function(data) {
                    var columns = data.match(/agenda_dag_events_column/g);
                    if (columns != null) {
                        columnCount = columns.length;
                    } else {
                        columnCount = 0;
                    }
                    
                    $('.agenda_dag_events').append(data);

                    $('.agenda_dag_events').css('width', ($("#agenda_scroll").attr('scrollWidth') + (238 * columnCount)) + 'px');
                    
                    dayEventsLimitStart = (dayEventsLimitStart + (columnCount * 3));
                    
                    busy = false; 
                }
            )
            
        }
        
        function loadMoreDaysInMonth(days)
        {
            var countriesStr = getFilterString(countries);
            var typesStr = getFilterStringTypes(types);
            var citiesStr = getFilterString(cities);
            
            monthLimitStart = (monthLimitStart + 1);
            
            $.post(rootUrl + 'agenda/month',
                {
                    'monthnumber': selectedMonth,
                    'yearnumber': selectedYear,
                    'limitstart': monthLimitStart,
                    'limitcount': days,
                    'more': '1',
                    'countries': countriesStr,
                    'types': typesStr,
                    'cities': citiesStr
                }, function(data) {
                    var width;
                    if((monthLimitStart + days) > daysInMonth(selectedMonth, selectedYear)) {
                        width = (daysInMonth(selectedMonth, selectedYear) - (monthLimitStart - 1)) * 102;
                    } else {
                        width = (days * 102);
                    }

                    $('.agenda_container').css('width', ($("#agenda_scroll").attr('scrollWidth') + width) + 'px');
                    $('.agenda_container').append(data);
                    if (days == 7) {
                        monthLimitStart = (monthLimitStart + 6);
                    }
                    busy = false;
                    $('.agenda_small_loader').hide();
                }
            );
        }
        
        function formatDate(fromDate, days, target) {
            var from = fromDate.split("_");
            
            // Retrieve the formatted date
            $.post(rootUrl + 'agenda/date',
                {
                    'daynumber': from[0],
                    'monthnumber': from[1],
                    'yearnumber': from[2],
                    'count': days
                }, function(data) {
                    $('.' + target).html(data);
                }
            );
        }

        function showLoadingBar()
        {
            $('.agenda_head_container').empty().html('<div style="text-align:center;margin-top: 200px;"><img src="' + rootUrl + 'public/images/default/Common/loader.gif" /></div>');
        }
        
        function getFilterString(type)
        {
            if (type.length == 0) {
                filterStr = 0;
            } else {
                filterStr = type.join('_');
            }
            return filterStr;
        }
        
        function getFilterStringTypes(type)
        {
            if (type.length == 0) {
                filterStr = 0;
            } else {
                newTypes = new Array();
                $(type).each(function() {
                    filterString = this.split('_');
                    $(filterString).each(function() {
                       if (this != 'type') {
                           newTypes.push(this);
                       } 
                    });
                })
                filterStr = newTypes.join('_');
            }
            return filterStr;
        }
        
        function daysInMonth(intMon,intYr)
        {
            switch(parseInt(intMon,10))
            {
                case 2:
                    if ((intYr%100)==0)
                        if ((intYr%400)==0) 
                            return 29;
                        else
                            return 28;
                    else if((intYr%4)==0)
                            return 29;
                    else
                        return 28;
                    break;
                case 4:
                    return 30
                    break;
                case 6:
                    return 30
                    break;
                case 9:
                    return 30
                    break;
                case 11:
                    return 30
                    break;
                default:
                    return 31;
                    break;
            }

        }
        
        function showDayEvents()
        {
            alert(dayEvents);
        }
        
        function filterTypesInputClick(typeId)
        {
            // Get the event type id which is (de)selected
            if (typeof(typeId) != 'object') {
                id = typeId;
            } else {
                id = $(this).attr('id');
            }
            // Check if there are values in the types array
            if (types.length > 0) {
                // If the event type id already in the types array is we remove it, otherwise we add it to the array
                if (jQuery.inArray(id, types) != -1) {
                    types = jQuery.grep(types, function(value) {
                        return value != id;
                    });
                } else {
                    types.push(id);
                }
            // If the types array is empty we can add it immediatly
            } else {
                types.push(id);
            }
        }
        
        function filterCitiesInputClick(cName)
        {
            if (typeof(cName) != 'object') {
                id = $('input[value=' + cName + ']').parent().attr('id').split('_');
                cityName = cName;
            } else {
                id = $(this).parent().attr('id').split('_');
                cityName = $(this).attr('value');
            }
            
            city =  $('span[class=agenda_city_name]', $('input[value=' + cityName + ']').parent()).html();
            city = trim(city);
            if ($('.jquery-checkbox', $('input[value=' + cityName + ']').parent()).hasClass('jquery-checkbox-checked')) {
                if (cities.length > 0) {
                    if (jQuery.inArray(city, cities) != -1) {
                        cities = jQuery.grep(cities, function(value) {
                            return value != city; 
                        });
                    }
                }
                
                html = '<li id="city_' + id[2] + '"><input type="checkbox" name="filter_cities" value="' + city + '" /> <span class="agenda_city_name">' + city + '</span></li>';
                
                if (id[2] == 0 || $('#filter_cities').children().length == 0) {
                    $('#filter_cities').prepend(html);
                } else {
                    parsed = false;
                    for (x = (parseInt(id[2]) - 1); x >= 0; x--) {
                        if($('#city_' + x).attr('id') != undefined) {
                            $('#city_' + x).after(html);
                            parsed = true;
                            break;
                        }
                    }
                    if (!parsed) {
                        $('#filter_cities').prepend(html);
                    }
                }
                
                $('input[value=' + cityName + ']', '#filter_cities_selected').parent().remove(); 
                $('input[value=' + city + ']').checkbox();
                $('input[name=filter_cities]').click(filterCitiesInputClick);
                 $('input[name=filter_cities_search]').keyup();
            } else {
                cities.push(cityName);
                
                $('#filter_cities_selected').append('<li id="sel_city_' + id[1] + '"><input type="checkbox" name="filter_cities" value="' + city + '" /> <span class="agenda_city_name">' + city + '</span></li>')
                $('input[value=' + cityName + ']', '#filter_cities').parent().remove();
                $('input[value=' + city + ']').checkbox();
                $('input[value=' + city + ']').click();
                $('input[name=filter_cities]').click(filterCitiesInputClick);
                if (typeof(cName) != 'string') {
                    $('#agenda_filter_cities')[0].scrollTo(0);
                }
            }
        }

        function filterCountriesInputClick(cid) {
            if (typeof(cid) != 'object') {
                countryId = cid;
            } else {
                countryId = $(this).attr('value');
            }
            
            id = $('input[value=' + countryId + ']:checkbox').parent().attr('id').split('_');
  
            country =  $('span[class=agenda_country_name]', $('input[value=' + countryId + ']:checkbox').parent()).html();
            country = trim(country);
            
            if ($('.jquery-checkbox', $('input[value=' + countryId + ']:checkbox').parent()).hasClass('jquery-checkbox-checked')) {
                if (countries.length > 0) {
                    if (jQuery.inArray(countryId, countries) != -1) {
                        countries = jQuery.grep(countries, function(value) {
                            return value != countryId; 
                        });
                    }
                }
                
                html = '<li id="country_' + id[2] + '"><input type="checkbox" name="filter_landen" value="' + countryId + '" /> <span class="agenda_country_name">' + country + '</span></li>';
                if (id[2] == 0 || $('#filter_landen').children().length == 0) {
                    $('#filter_landen').prepend(html);
                } else {
                    parsed = false;
                    for (x = (parseInt(id[2]) - 1); x >= 0; x--) {
                        if($('#country_' + x).attr('id') != undefined) {
                            $('#country_' + x).after(html);
                            parsed = true;
                            break;
                        }
                    }
                    if (!parsed) {
                        $('#filter_landen').prepend(html);
                    }
                }
                $('input[value=' + countryId + ']:checkbox', '#filter_landen_selected').parent().remove(); 
                $('input[value=' + countryId + ']:checkbox').checkbox();
                $('input[name=filter_landen]').click(filterCountriesInputClick);
                $('input[name=filter_ladnden_search]').keyup();
            } else {
                countries.push(countryId);
                
                $('#filter_landen_selected').append('<li id="sel_country_' + id[1] + '"><input type="checkbox" name="filter_landen" value="' + countryId + '" /> <span class="agenda_country_name">' + country + '</span></li>');
                $('input[value=' + countryId + ']:checkbox', '#filter_landen').parent().remove();
                $('input[value=' + countryId + ']:checkbox').checkbox();
                $('input[value=' + countryId + ']:checkbox').click();  
                $('input[name=filter_landen]').click(filterCountriesInputClick);
                $('#agenda_filter_landen')[0].scrollTo(0);
                
            }
        }

        function trim(value) {
          value = value.replace(/^\s+/,'');
          value = value.replace(/\s+$/,'');
          return value;
        }
    }
);

