/**
 * Init dyn catalog js functionality.
 */
$(function() {
    LoadingIndicator.hide();

    if ($("#journeySearch, #quickSearch").length > 0) {
        aida_dyn_catalog_initSearchform();
    }

    if ($("#searchStartDate, #searchEndDate").length > 0) {
        aida_dyn_catalog_initSearchDatePicker();
    }
});

var current_datepicker = null;

/**
 * Init dyn catlog search formular.
 */
function aida_dyn_catalog_initSearchform()
{
    aida_dyncat_searchbox_onChangeForm();

    /**
     * Updates earch form on user input.
     */
    $("#journeySearch").change(function(){
        aida_dyncat_searchbox_onChangeForm();
        aida_dyncat_searchbox_onChangeFormAjax();
    });
    /**
     * Updates earch form on user input.
     */
    $("#quickSearch").change(function(){
        aida_dyncat_searchbox_onChangeForm();
        aida_dyncat_searchbox_onChangeFormAjax();
    });
}

/**
 * Init search form date picker.
 */
function aida_dyn_catalog_initSearchDatePicker()
{
    $.datepicker.setDefaults($.datepicker.regional['de']);

    var dates = $("#searchStartDate, #searchEndDate").datepicker({
        // layout
        buttonImage: 'fileadmin/www.aida.de/v3/images/icon_calendar.gif',
        buttonImageOnly: true,
        showAnim: 'slideDown',

        // handling
        showOn: 'both',
        showOtherMonths: true,
        selectOtherMonths: true,
        constrainInput: true,

        // date validness
        shortYearCutoff: 99,
        minDate: +1,
        maxDate: aida_dyncat_searchbox_maxDate,

        // year and month selectboxes
        changeMonth: true,
        changeYear: true,

        /**
         * Update calendar when selcting date.
         *
         * Updates departure date calender with max date from retrun date selection
         * and update return calendar with min time from depareture selection
         *
         * @param selectedDate date selcted by user
         * @param inst DatePicker instance
         */
        onSelect: function(selectedDate, inst) {
            var option = this.id == "searchStartDate" ? "minDate" : "maxDate";
            var instance = $(this).data("datepicker");
            var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
            dates.not(this).datepicker("option", option, date);
            $("#journeySearch").change();
            $("#quickSearch").change();
        },

        /**
         *
         * @param input
         * @param inst
         * @returns
         */
        beforeShow: function(input, inst) {
            if (this.id == "searchStartDate") {
                // opening start date selection
                var d = $('#searchEndDate').val();
                if (d == '') {
                    return {
                        maxDate: aida_dyncat_searchbox_maxDate
                    };
                }
                // limit max date to slected searchEndDate
                var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, d, inst.settings);
                return {
                    maxDate: date
                };
            } else {
                // opening end date selection
                var d = $('#searchStartDate').val();
                if (d == '') {
                    return {
                        minDate: +1
                    };
                }
                var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, d, inst.settings);
                return {
                    minDate: date
                };
            }
        },

        /**
         *
         * @param date
         * @returns {Array}
         */
        beforeShowDay: function(date) {
            // add country selection for holidays
            // this needs to be done here,
            // because in beforeShow the DOM does not exists
            if ($('#country_selector_container').length == 0) {
                // get country selector template
                // defined in thos docuemnt inside hidden div
                var selector = $('#country_selector_template_container div').clone();

                // remember current datepicker, we need it later when
                // user selects another country for holidays
                current_datepicker = this.id;

                // append clone to datepicker
                $('#ui-datepicker-div').append(selector);

                // add ids to our clones
                selector.attr('id', 'country_selector_container');
                selector.children('select').attr('id', 'country_selector');

                // set selected country from template to our clone
                $('#country_selector').val($('#country_selector_template').val());

                /**
                 * update holidays when selecting another country
                 */
                selector.change(function(){
                    // store selected country in template
                    var val = $('#country_selector').val();
                    $('#country_selector_template').val(val);

                    // refresh calendar view
                    $('#' + current_datepicker).datepicker("refresh");
                });
            }

            // disable weekends,
            // day 6 (saturday) and 0 (sunday) returns 0 für modulo 6
            if (date.getDay() % 6 == 0) {
                return [true, 'weekend'];
            }

            if (typeof SPECIAL_DAYS == "undefined") {
                return [true, ''];
            }

            // highlight holidays
            var country = $('#country_selector').val();

            if (SPECIAL_DAYS[country]) {
                var holidays = SPECIAL_DAYS[country];

                var year  = date.getYear();
                if (year < 999) {
                    year += 1900;
                }
                var month = date.getMonth();

                if (holidays[year] && holidays[year][month]) {
                    var days = holidays[year][month];
                    var day  = date.getDate();

                    for (var i in days) {
                        if (days[i] == day) {
                            return [true, 'special'];
                        }
                    }
                }
            }

            // all other days are valid
            return [true, ''];
        }
    });
};

/**
 * Ändert die "display" Eigenschaft eines Elements entweder nach "flag" oder
 * genau ins Gegenteil der bisherigen Eigenschaft
 *
 * @param {string} element ElemtentsID
 * @param {boolean} flag "show"/"hide"
 */
function display(element, flag) {
    var el;
    if (el = document.getElementById(element)) {
        if (flag == 'hide') {
            display_value = 'none';
        } else if (flag == 'show') {
            display_value = 'block';
        } else if (el.style.display == 'none') {
            display_value = 'block';
        } else {
            display_value = 'none';
        }

        el.style.display = display_value;
    }
}

/**
 * Lässt ein Element periodisch "blinken"
 *
 * @param {string} element Element-ID
 */
function selectBlink(element)
{
    $('#' + element).effect('pulsate',{ times: 2 },200);
}

/**
 * Browse to next page in gallery
 *
 * @param {string} cruise_id
 */
function aida_dyncat_gallery_next(cruise_id)
{
    var aida_dyncat_gallery = document.getElementById('route_picture_gallery_' + cruise_id);
    aida_dyncat_gallery.scrollTop += 418;
    aida_dyncat_gallery_update_counter(cruise_id);
}

/**
 * Browse one page back in gallery
 *
 * @param {string} cruise_id
 */
function aida_dyncat_gallery_prev(cruise_id)
{
    var aida_dyncat_gallery = document.getElementById('route_picture_gallery_' + cruise_id);
    aida_dyncat_gallery.scrollTop -= 418;
    aida_dyncat_gallery_update_counter(cruise_id);
}

/**
 * Update page counter in gallery
 *
 * @param {string} cruise_id
 */
function aida_dyncat_gallery_update_counter(cruise_id)
{
    var aida_dyncat_gallery = document.getElementById('route_picture_gallery_' + cruise_id);
    var aida_dyncat_gallery_counter = document.getElementById('route_picture_gallery_counter_' + cruise_id);
    aida_dyncat_gallery_counter.textContent = aida_dyncat_gallery.scrollTop / 418 + 1;
    aida_dyncat_gallery_counter.innerText = aida_dyncat_gallery.scrollTop / 418 + 1;
}

/**
 * Starts gallery slideshow
 *
 * @param {string} cruise_id
 */
function aida_dyncat_gallery_start(cruise_id)
{
    Shadowbox.open(document.getElementById('route_picture_' + cruise_id + '_1'));
}

/**
 * Checks a given date and returns correct formated date if valid, or false if invalid
 * or true if empty.
 *
 * @param {string} date_string
 *
 * @return {Boolean|Date} false or correct date
 */
function aida_dyncat_checkDate(date_string)
{
    if (date_string.length < 1) {
        return true;
    }
    var date = date_string.split('.');

    // month in Date start from 0
    date[1] = date[1] - 1;

    var d = new Date(date[2],date[1],date[0]);
    if (d.getTime() < 1) {
        return false;
    }

    if (date[2] != d.getFullYear()) {
        return false;
    }
    if (date[1] != d.getMonth()) {
        return false;
    }
    if (date[0] != d.getDate()) {
        return false;
    }

    return d;
}

/**
 * Clear errors in searchbox
 */
function aida_dyncat_searchbox_clearError()
{
    $('.error').removeClass('error');
    $('#dyncat_searchbox_error').html('');
}

/**
 * Set error message and error class
 *
 * @param {string} message
 * @param element
 */
function aida_dyncat_searchbox_error(message, element)
{
    element.parent().parent().addClass('error');
    $('#dyncat_searchbox_error').html(
            $('#dyncat_searchbox_error').html()
            + '<p>' + message + '</p>'
    );
}

/**
 * Executes some validation
 */
function aida_dyncat_searchbox_onChangeForm()
{
    aida_dyncat_searchbox_clearError();

    var min_date = new Date();
    min_date.setHours(0);
    min_date.setMinutes(0);
    min_date.setSeconds(0);

    var start_date = aida_dyncat_checkDate($('#searchStartDate').val());

    if (start_date === false) {
        aida_dyncat_searchbox_error(
            textdb_p_dyncat_help_invalid_startdate_format,
            $('#searchStartDate')
        );
    } else if (start_date !== true) {
        if (start_date < min_date) {
            aida_dyncat_searchbox_error(
                textdb_p_dyncat_help_invalid_startdate_past,
                $('#searchStartDate')
            );
        }

        min_date = start_date;
    }

    var end_date = aida_dyncat_checkDate($('#searchEndDate').val());

    if (end_date === false) {
        aida_dyncat_searchbox_error(
            textdb_p_dyncat_help_invalid_enddate_format,
            $('#searchEndDate')
        );
    } else if (end_date !== true && end_date < min_date) {
        aida_dyncat_searchbox_error(
            textdb_p_dyncat_help_invalid_enddate_past,
            $('#searchEndDate')
        );
    }
}

/**
 * hide and show price overview
 */
function addBarObserver()
{
    //Hide (Collapse) the toggle containers on load
    // in fact hide all price information
    $(".bar .barContent").hide();

    //Switch the "Open" and "Close" state per click
    // make price information switchable show/hide
    $("#panel .result .bar h3").toggle(
        /**
         * Shows price information.
         */
        function(){
            //
            $(this).addClass("active");
            $(this).next(".bar .barContent").slideDown("slow");
        },
        /**
         * Hides price information.
         */
        function() {
            $(this).removeClass("active");
            $(this).next(".bar .barContent").slideUp("slow");
        }
    );
}

/**
 * reset Shadowbox Links after ajax reload
 */
function addShadowboxReset() {
    Shadowbox.clearCache();
    Shadowbox.setup();
}









/*global Aida:true */

if (typeof Aida !== 'object') {
    var Aida = {};
}

if (typeof Aida.DynCat !== 'object') {
    Aida.DynCat = {};
}


/**
 * Initialise page
 */
$(function() {
    Aida.DynCat.initSearchbox();
});

Aida.DynCat.cachedQueries = [];
Aida.DynCat.lastRegion = '';
Aida.DynCat.lastSeason = '';
Aida.DynCat.lastRoute = '';

/**
 * Initiliaze serach box
 */
Aida.DynCat.initSearchbox = function()
{
    var season = $( ".catalog_select" ).filter(":checked")[0];
    if (season) {
        Aida.DynCat.lastSeason = season.value;
    }

    var region = $( "#region_select .ui-selected" )[0];
    if (region) {
        Aida.DynCat.lastRegion = Aida.DynCat.lastSeason + region.id.split("_").pop();
    }
    
    var route = $( "#route_select .ui-selected" )[0];
    if (route) {
        Aida.DynCat.lastRoute = Aida.DynCat.lastRegion + route.id.split("_").pop();
    }
    
    /**
     * Handle load sub routes by selected region
     */
    $( ".catalog_select" ).click( function(event, ui)
        {
            var season_code = $(this).val();

            Aida.DynCat.loadRegions(season_code);
        }
    );

    /**
     * Handle load sub routes by selected region
     */
    $( "#region_select" ).selectable({
        selected: function(event, ui)
        {
            var strId = ui.selected.id;
            var region_code = strId.split("_").pop();

            var season_code = $( ".catalog_select" ).filter(":checked")[0].value;

            Aida.DynCat.loadRoutes(region_code, season_code);
        }
    });

    /**
     * Handle load route details by selected route
     */
    $( "#route_select" ).selectable({
        selected: function(event, ui)
        {
            var strId = ui.selected.id;
            var route_code = strId.split("_").pop();

            var strId = $( "#region_select .ui-selected" )[0].id;
            var region_code = strId.split("_").pop();

            var season_code = $( ".catalog_select" ).filter(":checked")[0].value;

            Aida.DynCat.loadRoutedetails(route_code, region_code, season_code);
        }
    });
}


/**
 * Loads routes for selected region.
 *
 * @param {String} region_code
 *
 * @return {String} output html list of subcategories
 */
Aida.DynCat.loadRegions = function(season_code)
{
    if (season_code == '') {
        var cache_key = 'all';
    } else {
        var cache_key = season_code;
    }
    
    if (Aida.DynCat.lastSeason == cache_key) {
        return;
    }
    
    Aida.DynCat.lastSeason = cache_key;
    
    if (Aida.DynCat.cachedQueries[cache_key]) {
        window.setTimeout(function() {
                Aida.DynCat.loadSuccess(Aida.DynCat.cachedQueries[cache_key]);
                Aida.DynCat.loadComplete();
            },
            1
        );
    } else {
        // Show overlay
        $.ajax({
            url: (ajaxUrl + '&tx_aidadyncatalog_catalog[searchRoutelistSeasonCode]=' + season_code),
            type: 'GET',
            timeout: 12000,
            dataType: 'html',
            success: function(html)
            {
                Aida.DynCat.loadSuccess(html, cache_key);
            },
            complete: Aida.DynCat.loadComplete
        });
    }
};



/**
 * Loads routes for selected region.
 *
 * @param {String} region_code
 *
 * @return {String} output html list of subcategories
 */
Aida.DynCat.loadRoutes = function(region_code, season_code)
{
    var cache_key = season_code + region_code;
    
    if (Aida.DynCat.lastRegion == cache_key) {
        return;
    }
    
    Aida.DynCat.lastRegion = cache_key;
    
    if (Aida.DynCat.cachedQueries[cache_key]) {
        window.setTimeout(function() {
            Aida.DynCat.loadSuccess(Aida.DynCat.cachedQueries[cache_key]);
            Aida.DynCat.loadComplete();
        },
        1
        );
    } else {
        // Show overlay
        $.ajax({
            url: (ajaxUrl + '&tx_aidadyncatalog_catalog[searchRoutelistRegionCode]=' + region_code),
            type: 'GET',
            timeout: 12000,
            dataType: 'html',
            success: function(html)
            {
                Aida.DynCat.loadSuccess(html, cache_key);
            },
            complete: Aida.DynCat.loadComplete
        });
    }
};



/**
 * Loads details for selected route.
 *
 * @param {String} route_code
 * @param {String} region_code
 *
 * @return {String} output html list of subcategories
 */
Aida.DynCat.loadRoutedetails = function(route_code, region_code, season_code)
{
    var cache_key = season_code + region_code + route_code;
    
    if (Aida.DynCat.lastRoute == cache_key) {
        return;
    }
    
    Aida.DynCat.lastRoute = cache_key;
    
    if (Aida.DynCat.cachedQueries[cache_key]) {
        window.setTimeout(function() {
                Aida.DynCat.loadSuccess(Aida.DynCat.cachedQueries[cache_key]);
                Aida.DynCat.loadComplete();
            },
            1
        );
    } else {
        // Show overlay
        $.ajax({
            url: (ajaxUrl + '&tx_aidadyncatalog_catalog[searchRoutelistRegionCode]=' + region_code + '&tx_aidadyncatalog_catalog[searchRoutelistRouteCode]=' + route_code),
            type: 'GET',
            timeout: 12000,
            dataType: 'html',
            success: function(html)
            {
                Aida.DynCat.loadSuccess(html, cache_key);
            },
            complete: Aida.DynCat.loadComplete
        });
    }
};


/**
 *
 * @param {String} html
 * @param {String} cache_key
 */
Aida.DynCat.loadSuccess = function(html, cache_key)
{
    if (cache_key) {
        Aida.DynCat.cachedQueries[cache_key] = html;
    }

    $('#dyncatSearchSwitch').html(html);
    $("#dyncatSearchSwitch a.tabanchor").each(function() {
        var anchorname = $(this).attr("href");
        anchorname = anchorname.substring(anchorname.indexOf('#'));
        $(this).attr("href", anchorname);
    });

    $("#dyncatSearchSwitch").tabs("select", "panel3");
};


/**
 *
 */
Aida.DynCat.loadComplete = function(XMLHttpRequest, textStatus)
{
    Aida.DynCat.initSearchbox();
};

