window.addEvent('booking-period-domready', function () {

    var periodTimeFrame = document.id('period_timeframe');
    var periodType = document.id('period_type');
    var periodPriceId = document.id('period_price_id');

    var periodTypeDaily = document.id('period_type_daily');
    var periodTypeWeekly = document.id('period_type_weekly');
    var periodTypeMonthly = document.id('period_type_monthly');
    var periodTypeYearly = document.id('period_type_yearly');

    var periodTypes = [periodTypeDaily, periodTypeWeekly, periodTypeMonthly, periodTypeYearly];

    var periodRecurrence = document.id('period_recurrence');

    var periodSundayCheckbox = document.id('period_sunday_checkbox');
    var periodMondayCheckbox = document.id('period_monday_checkbox');
    var periodTuesdayCheckbox = document.id('period_tuesday_checkbox');
    var periodWednesdayCheckbox = document.id('period_wednesday_checkbox');
    var periodThursdayCheckbox = document.id('period_thursday_checkbox');
    var periodFridayCheckbox = document.id('period_friday_checkbox');
    var periodSaturdayCheckbox = document.id('period_saturday_checkbox');

    var periodDayCheckbox = [periodMondayCheckbox, periodTuesdayCheckbox, periodWednesdayCheckbox, periodThursdayCheckbox, periodFridayCheckbox, periodSaturdayCheckbox, periodSundayCheckbox];

    var periodMondayHidden = document.id('period_monday_hidden');
    var periodTuesdayHidden = document.id('period_tuesday_hidden');
    var periodWednesdayHidden = document.id('period_wednesday_hidden');
    var periodThursdayHidden = document.id('period_thursday_hidden');
    var periodFridayHidden = document.id('period_friday_hidden');
    var periodSaturdayHidden = document.id('period_saturday_hidden');
    var periodSundayHidden = document.id('period_sunday_hidden');

    var periodDayHidden = [periodMondayHidden, periodTuesdayHidden, periodWednesdayHidden, periodThursdayHidden, periodFridayHidden, periodSaturdayHidden, periodSundayHidden];

    var periodWeek = document.id('period_week');
    var periodDay = document.id('period_day');
    var periodMonth = document.id('period_month');

    var periodDateUp = document.id('period_date_up');
    var periodDateUpDa = document.id('period_date_up');

    var periodEndNo = document.id('period_end_no');
    var periodOccurrences = document.id('period_occurrences');
    var periodDateDown = document.id('period_date_down');

    var periodEndTypes = [periodEndNo, periodOccurrences, periodDateDown];

    var periodOccurrencesOccurrences = document.id('period_occurrences_occurrences');
    var periodDateDownDate = document.id('period_date_down_date');
    var periodDateDownDateDa = document.id('period_date_down_date_da');

    var periodDateUpImg = document.id('period_date_up_img');
    var periodDateDownDateImg = document.id('period_date_down_date_img');

    var periodRtypeId = document.id('period_rtype_id');
    var periodTimeUp = document.id('period_time_up');
    var periodTimeDown = document.id('period_time_down');

    var dailyWeekly = document.id('daily_weekly');
    var monthlyYearly = document.id('monthly_yearly');
    var recurrence = document.id('recurrence');

    var capacity = document.id('capacity');

    document.getElements('*[id^="period_"], #capacity').each(function (e) {
        e.addEvent('booking-period-error', function () {
            this.addClass('error');
            var label = document.getElement('label[for="' + this.id + '"]');
            if (label) {
                label.addClass('error');
            }
        });
        e.addEvent('booking-period-valid', function () {
            this.removeClass('error');
            var label = document.getElement('label[for="' + this.id + '"]');
            if (label) {
                label.removeClass('error');
            }
        });
    });

    periodDateDownDateImg.hide();

    if (periodType) {
        periodType.addEvent('change', function () {
            var cid = this.value.split('.');
            ['period_time_up_multi', 'period_time_down_multi'].each(function (field) {
                document.getElements('select[id^="' + field + '"]').each(function (select) {
                    var show = select.id === field + cid[1];
                    select.setStyle('display', show ? '' : 'none');
                    select.disabled = !show;
                    if (show && field === 'period_time_down_multi' && select.options.length > 1) {
                        select.disabled = true;
                    }
                });
            });
            periodRtypeId.value = cid[0];
            periodPriceId.value = cid[1];

            periodTypes.each(function (type) {
                if (type.checked) {
                    type.fireEvent('click');
                }
            });
        }).fireEvent('change');
        document.getElements('select[name="period_time_up"]').each(function (select) {
            select.addEvent('change', function () {
                var down = document.id(this.id.replace('period_time_up_multi', 'period_time_down_multi'));
                down.disabled = this.value === '0';
                down.value = down.selectedIndex = 0;
                var fix = getTimeFrameData('fix').toInt();
                var mul = getTimeFrameData('fix-multiply').toInt();
                var min = getTimeFrameData('min').toInt();
                var max = getTimeFrameData('max').toInt();
                for (var o = 1; o < down.options['length']; o++) {
                    var off = o - this.selectedIndex + 1;
                    down.options[o].disabled =
                        this.selectedIndex > o ||
                        (fix > 0 && mul === 0 && off !== fix) ||
                        (fix > 0 && mul === 1 && off % fix !== 0) ||
                        (fix < 1 && min > 0 && off < min) ||
                        (fix < 1 && max > 0 && off > max);
                }
            });
        });
    }

    periodTimeFrame.addEvent('change', function () {
        if (this.selectedIndex > 0 || this.options.length === 1) {
            var option = this.options[this.selectedIndex];
            periodRtypeId.value = option.get('data-rtype-id');
            periodPriceId.value = option.get('data-price-id');
            periodTimeUp.value = option.get('data-up');
            periodTimeDown.value = option.get('data-down');
        }
        periodTypes.each(function (type) {
            if (type.checked) {
                type.fireEvent('click');
            }
        });
    });

    document.getElements('select[id^="period_"], #capacity').each(function (select) {
        select.addEvent('click', function () {
            if (this.value !== '') {
                this.fireEvent('booking-period-valid');
            }
        });
    });

    periodTypes.each(function (type) {
        type.addEvent('click', function () {
            periodTypes.each(function (type) {
                type.fireEvent('booking-period-valid');
            });
        });
    });

    [periodRecurrence, periodDateUp, periodDateDownDate, periodOccurrencesOccurrences].each(function (e) {
        e.addEvent('change', function () {
            if (this.value !== '') {
                this.fireEvent('booking-period-valid');
            }
        });
    });

    periodDateUpImg.addEvent('click', function () {
        periodDateUp.fireEvent('booking-period-valid');
        periodDateUpDa.fireEvent('booking-period-valid');
    });

    periodDateDownDateImg.addEvent('click', function () {
        periodDateDownDate.fireEvent('booking-period-valid');
        periodDateDownDateDa.fireEvent('booking-period-valid');
        periodDateDown.fireEvent('booking-period-valid');
    });

    function getPeriodWeekDays() {
        return JSON.decode(getTimeFrameData('week-days'));
    }

    function getTimeFrameData(data) {
        return periodType ?
            periodType.options[periodType.selectedIndex].get('data-' + data) :
            periodTimeFrame.options[periodTimeFrame.selectedIndex].get('data-' + data);
    }

    periodTypeDaily.addEvent('click', function () {
        dailyWeekly.show();
        recurrence.hide();
        monthlyYearly.hide();

        var weekDays = getPeriodWeekDays();

        periodDayCheckbox.each(function (day, i) {
            day.checked = weekDays[i] === 1;
            day.disabled = true;
        });

        periodDayHidden.each(function (day, i) {
            day.value = weekDays[i];
        });

        periodRecurrence.value = '1';
        periodMonth.value = periodWeek.value = periodDay.value = '';
    });

    periodTypeWeekly.addEvent('click', function () {

        dailyWeekly.show();
        recurrence.show();
        monthlyYearly.hide();

        var weekDays = getPeriodWeekDays();

        periodDayCheckbox.each(function (day, i) {
            day.disabled = weekDays[i] === 0;
            day.checked = false;
        });

        periodDayHidden.each(function (day, i) {
            day.value = 0;
        });

        periodRecurrence.value = periodMonth.value = periodWeek.value = periodDay.value = '';
    });

    periodTypeMonthly.addEvent('click', function () {
        dailyWeekly.hide();
        monthlyYearly.show();
        periodMonth.hide();

        periodDayCheckbox.each(function (day, i) {
            day.checked = false;
        });

        periodDayHidden.each(function (day, i) {
            day.value = 0;
        });

        periodRecurrence.value = periodMonth.value = '';

        var weekDays = getPeriodWeekDays();

        weekDays.each(function (day, i) {
            periodDay.options[i + 1].disabled = day === 0;
        });
    });

    periodTypeYearly.addEvent('click', function () {
        dailyWeekly.hide();
        monthlyYearly.show();
        periodMonth.show();

        periodDayCheckbox.each(function (day, i) {
            day.checked = false;
        });

        periodDayHidden.each(function (day, i) {
            day.value = 0;
        });

        periodRecurrence.value = '';

        var weekDays = getPeriodWeekDays();

        weekDays.each(function (day, i) {
            periodDay.options[i + 1].disabled = day === 0;
        });
    });

    periodEndNo.addEvent('click', function () {
        periodOccurrencesOccurrences.disabled = true;
        periodDateDownDateImg.hide();
        periodOccurrencesOccurrences.value = '';
        periodDateDownDate.value = '';
        periodDateDownDateDa.set('html', '');
    });

    periodOccurrences.addEvent('click', function () {
        periodOccurrencesOccurrences.disabled = false;
        periodDateDownDateImg.hide();
        periodDateDownDate.value = '';
        periodDateDownDateDa.set('html', '');
    });

    periodDateDown.addEvent('click', function () {
        periodOccurrencesOccurrences.disabled = true;
        periodDateDownDate.disabled = false;
        periodDateDownDateImg.show();
        periodOccurrencesOccurrences.value = '';
    });

    periodDayCheckbox.each(function (day) {
        day.addEvent('click', function () {
            periodDayCheckbox.each(function (day) {
                day.fireEvent('booking-period-valid');
            });
        });
    });

    periodEndTypes.each(function (end) {
        end.addEvent('click', function () {
            periodEndTypes.each(function (end) {
                end.fireEvent('booking-period-valid');
            });
            periodOccurrencesOccurrences.fireEvent('booking-period-valid');
            periodDateDownDate.fireEvent('booking-period-valid');
            periodDateDownDateDa.fireEvent('booking-period-valid');
        });
    });

    periodMondayCheckbox.addEvent('click', function () {
        periodMondayHidden.value = this.checked ? 1 : 0;
    });

    periodTuesdayCheckbox.addEvent('click', function () {
        periodTuesdayHidden.value = this.checked ? 1 : 0;
    });

    periodWednesdayCheckbox.addEvent('click', function () {
        periodWednesdayHidden.value = this.checked ? 1 : 0;
    });

    periodThursdayCheckbox.addEvent('click', function () {
        periodThursdayHidden.value = this.checked ? 1 : 0;
    });

    periodFridayCheckbox.addEvent('click', function () {
        periodFridayHidden.value = this.checked ? 1 : 0;
    });

    periodSaturdayCheckbox.addEvent('click', function () {
        periodSaturdayHidden.value = this.checked ? 1 : 0;
    });

    periodSundayCheckbox.addEvent('click', function () {
        periodSundayHidden.value = this.checked ? 1 : 0;
    });

    var calculateRecurrences = document.id('calculateRecurrences');
    var calculateRecurrencesSpan = document.getElement('#calculateRecurrences div');
    var calculateTotal = document.id('calculateTotal');
    var calculateError = document.id('calculateError');
    var calculateLoader = document.id('calculateLoader');

    document.getElements('#bookIt, #calculateBookIt').each(function (button) {
        button.addEvent('click', function (event) {
            if (periodTimeFrame && periodTimeFrame.value == '' && !periodType) {
                periodTimeFrame.fireEvent('booking-period-error');
                return false;
            }

            if (periodType && periodType.value == '') {
                periodType.fireEvent('booking-period-error');
                return false;
            }

            var multiUp = document.id('period_time_up_multi' + periodPriceId.value);
            var multiDown = document.id('period_time_down_multi' + periodPriceId.value);
            if (multiUp && multiDown) {
                if (multiUp.value == '' || multiDown.value == '') {
                    multiUp.fireEvent('booking-period-error');
                    multiDown.fireEvent('booking-period-error');
                    return false;
                } else if (multiUp.value >= multiDown.value && multiDown.value != '00:00:00') {
                    multiUp.fireEvent('booking-period-error');
                    multiDown.fireEvent('booking-period-error');
                    return false;
                }
            }

            if (!(periodTypeDaily.checked || periodTypeWeekly.checked || periodTypeMonthly.checked || periodTypeYearly.checked)) {
                periodTypes.each(function (type) {
                    type.fireEvent('booking-period-error');
                })
                return false;
            }

            if (periodTypeWeekly.checked && !periodRecurrence.value.match(/^[1-9]+[0-9]*$/)) {
                periodRecurrence.fireEvent('booking-period-error');
                return false;
            }

            if (periodTypeWeekly.checked && !(periodSundayCheckbox.checked || periodMondayCheckbox.checked || periodTuesdayCheckbox.checked || periodWednesdayCheckbox.checked || periodThursdayCheckbox.checked || periodFridayCheckbox.checked || periodSaturdayCheckbox.checked)) {
                periodDayCheckbox.each(function (day) {
                    if (!day.disabled) {
                        day.fireEvent('booking-period-error');
                    }
                });
                return false;
            }

            if (periodTypeYearly.checked && periodMonth.value == '') {
                periodMonth.fireEvent('booking-period-error');
                return false;
            }

            if ((periodTypeMonthly.checked || periodTypeYearly.checked) && periodWeek.value == '') {
                periodWeek.fireEvent('booking-period-error');
                return false;
            }

            if ((periodTypeMonthly.checked || periodTypeYearly.checked) && periodDay.value == '') {
                periodDay.fireEvent('booking-period-error');
                return false;
            }

            if (periodDateUp.value == '') {
                periodDateUp.fireEvent('booking-period-error');
                periodDateUpDa.fireEvent('booking-period-error');
                return false;
            } else {
                var d = new Date();
                if (periodDateUp.value < d.format('%Y-%m-%d')) {
                    periodDateUp.fireEvent('booking-period-error');
                    periodDateUpDa.fireEvent('booking-period-error');
                    return false;
                }
            }

            if (!(periodEndNo.checked || periodOccurrences.checked || periodDateDown.checked)) {
                periodEndTypes.each(function (end) {
                    end.fireEvent('booking-period-error');
                })
                return false;
            }

            if (periodOccurrences.checked && !periodOccurrencesOccurrences.value.match(/^[1-9]+[0-9]*$/)) {
                periodOccurrencesOccurrences.fireEvent('booking-period-error');
                return false;
            }

            if (periodDateDown.checked && periodDateDownDate.value == '') {
                periodDateDownDate.fireEvent('booking-period-error');
                periodDateDownDateDa.fireEvent('booking-period-error');
                periodDateDown.fireEvent('booking-period-error');
                return false;
            }

            if (periodDateDown.checked && periodDateUp.value > periodDateDownDate.value) {
                periodDateUp.fireEvent('booking-period-error');
                periodDateDownDate.fireEvent('booking-period-error');
                periodDateDownDateDa.fireEvent('booking-period-error');
                periodDateDown.fireEvent('booking-period-error');
                return false;
            }

            if (capacity && capacity.value.toInt() < 1) {
                capacity.fireEvent('booking-period-error');
                return false;
            }

            if (button.id === 'bookIt') {
                document.bookSetting.controller.value = 'reservation';
                document.bookSetting.task.value = 'addPeriod';
                Calendars.bookIt();
                return true;
            } else {
                document.bookSetting.controller.value = 'reservation';
                document.bookSetting.task.value = 'gettotal';
                new Request({
                    method: 'post',
                    url: '/',
                    data: document.bookSetting.toQueryString(),
                    onRequest : function () {
                        calculateLoader.show();
                    },
                    onComplete: function(response) {
                        calculateLoader.hide();
                        response = JSON.decode(response);
                        if (response.status === 'OK') {
                            calculateTotal.set('html', response.total);
                            calculateError.set('html', '');
                        } else {
                            calculateTotal.set('html', '');
                            calculateError.set('html', response.error);
                        }
                        if (response.period) {
                            calculateRecurrences.show();
                            calculateRecurrencesSpan.set('html', response.period);
                        } else {
                            calculateRecurrences.hide();
                            calculateRecurrencesSpan.set('html', '');
                        }
                    }
                }).send();
                return false;
            }
        });
    });

    periodTimeFrame.fireEvent('change');
});