/* eslint-disable */
var Calendar_Form = {};

(function (window, document, obj, undefined) {
    "use strict";

    /**
     * trigger Event when the user clicks on a specific checkbox : display / hide options with a transition
     */
    obj.checkboxClickTransition = function (element) {
        var elementIsChecked = element.is(':checked'),
            elementId = element.attr('id'),
            elementContainer = $('div[data-af-target="' + elementId + '"]'),
            elementValue = elementContainer.data('af-triggered-value');

        if (elementContainer.length > 0) {
            if (elementValue === undefined) {
                elementValue = true;
            }

            if (elementIsChecked === elementValue) {
                elementContainer.slideDown({
                    duration: 'slow',
                    start: function () {
                        elementContainer.find('[data-af-default-value]').each(function () {
                            if ($(this).val().length === 0) {
                                $(this).val($(this).data('af-default-value'));
                            }
                        });
                    },
                });
            } else {
                elementContainer.slideUp('slow', function () {
                });
            }
        }
    };

    obj.getVisibility = function(element) {
        var options = {
            limited_date_access: true,
            limited_seats_rules: true,
            limited_reservation_rules: true,
            logged_rules: true,
            multicast_rules: false
        };
        element.parents('.' + Calendar_AgendaTicket.classContainer).find('[data-af-ticket-show-options]').each(function() {
            var keys = (jQuery(this).attr('data-af-ticket-show-options') || '').split(','), i;
            if (jQuery(this).is(':checked')) {
                for(i = 0 ; i < keys.length ; i++) {
                    options[keys[i]] = true;
                }
            }
        });
        element.parents('.' + Calendar_AgendaTicket.classContainer).find('[data-af-ticket-hide-options]').each(function() {
            var keys = (jQuery(this).attr('data-af-ticket-hide-options') || '').split(','), i;
            if (jQuery(this).is(':checked')) {
                for(i = 0 ; i < keys.length ; i++) {
                    options[keys[i]] = false;
                }
            }
        });
        return options;
    };

    obj.updateInputVisibility = function (element) {
        var options = this.getVisibility(element);
        jQuery.each(options, function(key) {
            if(options[key]) {
                element.parents('.' + Calendar_AgendaTicket.classContainer).find('[data-af-name="' + key + '"]').show();
            } else {
                element.parents('.' + Calendar_AgendaTicket.classContainer).find('[data-af-name="' + key + '"]').hide();
            }
        });
    };

    obj.updateInputVisibilityTransition = function (element) {
        var options = this.getVisibility(element);
        jQuery.each(options, function(key) {
            if(options[key]) {
                element.parents('.' + Calendar_AgendaTicket.classContainer).find('[data-af-name="' + key + '"]').slideDown();
            } else {
                element.parents('.' + Calendar_AgendaTicket.classContainer).find('[data-af-name="' + key + '"]').slideUp();
            }
        });
    };

    /**
     * trigger Event when the user clicks on a specific checkbox : display / hide options
     */
    obj.checkboxClick = function (element) {
        var elementIsChecked = element.is(':checked'),
            elementId = element.attr('id'),
            elementContainer = $('div[data-af-target="' + elementId + '"]'),
            elementValue = elementContainer.data('af-triggered-value');

        if (elementContainer.length > 0) {
            if (elementValue === undefined) {
                elementValue = true;
            }
            if (elementIsChecked === elementValue) {
                elementContainer.show();
            } else {
                elementContainer.hide();
            }
        }
    };

    obj.registerEvents = function () {
        var container = $('#add_event_form');

        container.find(' input[type="checkbox"]').each(function () {
            Calendar_Form.checkboxClick($(this));
            Calendar_Form.updateInputVisibility($(this));
        });

        container.off('click keyup').on('click keyup', function (e) {
            var elmt = $(e.target),
                role = elmt.data('af-role');

            if (role === undefined) {
                return true;
            }

            switch (role) {
                case 'could-rsvp' :
                    Calendar_AgendaOptions.couldRsvpTriggerTransition(elmt);
                    break;
                case 'limited-date-access':
                case 'limited-seats':
                case 'limited-reservation':
                case 'restrict-rule-contribution':
                case 'restrict-rule-subscription':
                case 'restrict-rule-user-type':
                case 'accept-coupon-category':
                case 'limited':
                    Calendar_Form.checkboxClickTransition(elmt);
                    break;
                case 'external-registration':
                    Calendar_Form.checkboxClickTransition(elmt);
                    break;
                case 'open-event':
                    Calendar_Form.updateInputVisibilityTransition(elmt);
                    Calendar_AgendaTicket.displayExternalFields();
                    break;
                case 'multicast-price':
                    Calendar_Form.updateInputVisibilityTransition(elmt);
                    Calendar_AgendaTicket.displayExternalFields();
                    break;
                case 'agenda-ticket-add':
                    Calendar_AgendaTicket.createNewTicketForm();
                    break;
                case 'agenda-ticket-copy' :
                    var sourceTicketContainer = elmt.parents('.agenda-ticket-container').parent();
                    Calendar_AgendaTicket.copyTicketForm(sourceTicketContainer);
                    break;
                case 'agenda-ticket-delete':
                    var targetTicketContainer = elmt.parents('.agenda-ticket-container').parent();

                    if (confirm(Calendar_AgendaTicket.deleteAlertLabel)) {
                        var needToScroll = targetTicketContainer.is(':last-child');
                        Calendar_AgendaTicket.removeTicket(targetTicketContainer);

                        if (needToScroll) {
                            var scrollToTarget = $('.agenda-ticket-actions').last();
                            if (scrollToTarget.not(':first-child')) {
                                Calendar_AgendaTicket.scrollToTicket(scrollToTarget.parent());
                            }
                        }
                    }
                    break;
                case 'ticketSeatTotal' :
                    Calendar_AgendaTicket.populateGlobalSeatField();
                    break;
                case 'displayExternalField':
                    Calendar_ExternalFields.displayExternalField(elmt);
                    break;
                case 'requiredExternalField':
                    Calendar_ExternalFields.requiredExternalField(elmt);
                    break;
                case 'onlinePayment' :
                    Calendar_ExternalFields.checkDefaultExternalFields(elmt);
                    break;
                case 'nav-element' :
                    Calendar_Form_Status.switchTab(elmt);
                    break;
                default:
                    return true;
            }

            e.stopPropagation();
        });
    };
}(window, document, Calendar_Form));

var Calendar_AgendaTicket = {};

(function (window, document, obj, undefined) {
    "use strict";
    obj.classContainer = 'agenda-ticket';
    obj.subformPrefix = '';
    obj.maxAgendaTickets = -1;
    obj.ticketLabel = '';
    obj.removeIconClass = '';
    obj.deleteAlertLabel = '';
    obj.event = {};


    /**
     * Create a new ticket based on the standard template of the ticket
     */
    obj.createNewTicketForm = function () {
        var countTickets = Calendar_AgendaTicket.countTickets();

        if (Calendar_AgendaTicket.maxAgendaTickets === -1 || (countTickets + 1) < Calendar_AgendaTicket.maxAgendaTickets) {
            var firstTicketContainer = $('#' + Calendar_AgendaTicket.classContainer + '-1'),
                targetTicketContainer = Calendar_AgendaTicket.addNewTicket(firstTicketContainer);
            Calendar_AgendaTicket.flushTicket(targetTicketContainer);

            // set selected languages
            targetTicketContainer.find('.lang_selector option[selected]').attr('selected', 'selected');

            // select the first option in the new container contrib multi-select
            var targetContainerId = targetTicketContainer.attr('id');
            var targetContainerUniqId = targetContainerId.split('-')[2];
            var newContainerContribSelect = $('#agendatickets' + targetContainerUniqId + '-restrict_rule_contribution_pack_ids');
            newContainerContribSelect.val('0');

            // select the first option in the new container subscription multi-select
            var newContainerSubscriptionSelect = $('#agendatickets' + targetContainerUniqId + '-restrict_rule_subscription_type_ids');
            newContainerSubscriptionSelect.val('0');

            // select the first option in the coupon category multi-select
            jQuery('#agendatickets' + targetContainerUniqId + '-accept_coupon_category_ids').val('0');

            if (firstTicketContainer.find('[data-af-hide="open_event"] :checkbox').prop('checked')) {
                targetTicketContainer.find('[data-af-hide="open_event"] :checkbox').prop('checked', true);
            }
        } else {
            // TODO : do something if there are too many tickets
        }
    };

    /**
     * Add new Ticket to the Dom
     */
    obj.addNewTicket = function (elmt) {
        var currentTicket = elmt.clone(true),
            ticket = currentTicket.find('.agenda-ticket-container'),
            ticketHtml = currentTicket.html(),
            ticketId = ticket.data('af-ticket-id'),
            uniqId = Calendar_AgendaTicket.generateUniqId(),
            newTicketId = Calendar_AgendaTicket.getNewTicketId(uniqId),
            replaceRegex = new RegExp(ticketId, 'gi'),
            newTicketHtml = ticketHtml.replace(replaceRegex, newTicketId),
            jQueryNewTicket = $(newTicketHtml),
            countTickets = Calendar_AgendaTicket.countTickets() + 1,
            ticketLabel = Calendar_AgendaTicket.ticketLabel.replace('%s', countTickets),
            targetTicketContainerId = Calendar_AgendaTicket.classContainer + '-' + uniqId,
            targetTicketContainer = $('<div id="' + targetTicketContainerId + '" data-test="ticket-setting"></div>'),
            couldRemoveTicket = jQueryNewTicket.find('.agenda-ticket-actions [data-af-role="agenda-ticket-delete"]').length;

        if (!couldRemoveTicket) {
            Calendar_AgendaTicket.addRemoveAction(jQueryNewTicket);
        }

        jQueryNewTicket.find('[data-af-role="agenda-ticket-title"]').html(ticketLabel);
        jQueryNewTicket.find('#' + newTicketId + '-id').val('');

        jQueryNewTicket.find('[data-translate-parent]').attr('data-translate-parent', '#' + targetTicketContainerId);
        jQueryNewTicket.find('[data-parent-target]').attr('data-parent-target', '#' + targetTicketContainerId);
        jQueryNewTicket.find('[data-subform-name]').attr('data-subform-name', newTicketId);

        targetTicketContainer.append(jQueryNewTicket);

        $('#agenda-tickets-container').append(targetTicketContainer);

        jQueryNewTicket.find('textarea').each(function () {
            Mevia_FieldCounter.init($(this).attr('id'));
        });

        // get the original datepicker options
        var origElmt = elmt.find('.hasDatepicker').attr('id'),
            options = {};
        if (!!origElmt) {
            options = $('#' + origElmt).datepicker('option', 'all');
        }
        jQueryNewTicket.find('.calendar:input').each(function () {
            $(this).removeClass('hasDatepicker');
            $(this).datetimepicker('destroy').datetimepicker(options);
        });

        Calendar_AgendaTicket.populateGlobalSeatField();

        jQuery('#'+targetTicketContainerId+' .chosen-container').remove(); // remove all copied chosen containers
        jQuery.each(jQuery('#'+targetTicketContainerId+' .chosen'), window.chosenDispatcher); // dispatch chosen to generate element with attached events

        return targetTicketContainer;
    };

    /**
     * Create a new ticket based on the template of the ticket to be cloned
     */
    obj.copyTicketForm = function (sourceTicketContainer) {
        var countTickets = Calendar_AgendaTicket.countTickets();

        if (Calendar_AgendaTicket.maxAgendaTickets == -1 || (countTickets + 1) < Calendar_AgendaTicket.maxAgendaTickets) {
            var targetTicketContainer = Calendar_AgendaTicket.addNewTicket(sourceTicketContainer);
            Calendar_AgendaTicket.fillTicket(targetTicketContainer, sourceTicketContainer);
            Calendar_AgendaTicket.scrollToTicket(targetTicketContainer);
        } else {
            // TODO : do something if there are too many tickets
        }
    };

    /**
     * Remove a ticket
     */
    obj.removeTicket = function (targetTicketContainer) {
        targetTicketContainer.remove();

        var i = 1;
        $('#agenda-tickets-container').find('.agenda-ticket-container').each(function () {
            var ticketLabel = Calendar_AgendaTicket.ticketLabel.replace('%s', i);

            $(this).find('[data-af-role="agenda-ticket-title"]').html(ticketLabel);
            i++;
        });
        Calendar_AgendaTicket.populateGlobalSeatField();
    };

    /**
     * Flush fields of a ticket
     */
    obj.flushTicket = function (targetTicketContainer) {
        var jQueryTargetTicketContainer = $(targetTicketContainer);
        Calendar_AgendaTicket.flushFields(jQueryTargetTicketContainer);
    };

    /**
     * Flush fields for a specific container
     */
    obj.flushFields = function (container) {
        container.find(':input').not(':checkbox, :radio').val('');
        container.find('textarea').html('');
        container.find('textarea').trigger('keyup');
        container.find(':checkbox, :radio').prop('checked', false);
        container.find(':checkbox').each(function () {
            Calendar_Form.checkboxClick($(this));
        });
    };

    /**
     * Fill the target Ticket with the data of the source Ticket
     */
    obj.fillTicket = function (targetTicketContainer, sourceTicketContainer) {
        var jQueryTargetTicketContainer = $(targetTicketContainer),
            jQueryTicketId = jQueryTargetTicketContainer.find('.agenda-ticket-container').data('af-ticket-id'),
            jQuerySourceTicketContainer = $(sourceTicketContainer),
            jQueryTargetTicketId = jQuerySourceTicketContainer.find('.agenda-ticket-container').data('af-ticket-id');

        jQuerySourceTicketContainer.find(':input, textarea').not(':checkbox, :radio, :hidden').each(function () {
            var sourceFieldId = $(this).attr('id'),
                sourceFieldValue = $(this).val(),
                targetFieldId = sourceFieldId.replace(jQueryTargetTicketId, jQueryTicketId);

            jQueryTargetTicketContainer.find('#' + targetFieldId).val(sourceFieldValue);
        });

        jQuerySourceTicketContainer.find(':checkbox, :radio').each(function () {
            var sourceFieldId = $(this).attr('id'),
                sourceFieldValue = $(this).is(':checked'),
                targetFieldId = sourceFieldId.replace(jQueryTargetTicketId, jQueryTicketId);
            jQueryTargetTicketContainer.find('#' + targetFieldId).prop('checked', sourceFieldValue);
            Calendar_Form.checkboxClick($(this));
        });

        jQueryTargetTicketContainer.find('textarea').trigger('keyup');
    };

    /**
     * Generate a uniq ID
     */
    obj.generateUniqId = function () {
        return Math.floor(Math.random() * 100000000);
    };

    /**
     * Get the new ticket Id
     */
    obj.getNewTicketId = function (uniqId) {
        return Calendar_AgendaTicket.subformPrefix + uniqId;
    };

    /**
     * Count created tickets
     */
    obj.countTickets = function () {
        return $('.agenda-ticket-container').length
    };

    /**
     * Scroll to the ticket with an animation
     */
    obj.scrollToTicket = function (targetTicketContainer) {
        var scrollPosition = targetTicketContainer.position();
        scrollPosition = scrollPosition.top - 10;

        $('html, body').animate({scrollTop: scrollPosition}, 'slow');
    };

    /**
     * Add the remove action to a ticket
     */
    obj.addRemoveAction = function (targetTicketContainer) {
        var removeContainer = targetTicketContainer.find('.agenda-ticket-actions'),
            removeTag = $('<i class="' + Calendar_AgendaTicket.removeIconClass + ' cursor" data-af-role="agenda-ticket-delete"/>');

        removeContainer.append(removeTag);
    };

    /**
     * Display the external fields
     */
    obj.displayExternalFields = function () {
        var checked = $('.agenda-ticket-container [data-af-role="open-event"]:checked').length
          || $('.agenda-ticket-container [data-af-role="multicast-price"]:checked').length;

        if (checked > 0) {
            $('#external_fields').slideDown();
        } else {
            $('#external_fields').slideUp();
        }
    };
    /**
     * Initialize events
     */
    obj.initEvents = function () {
        Calendar_AgendaOptions.couldRsvpTrigger(jQuery('#could_rsvp'));
        Calendar_AgendaTicket.displayExternalFields();
    };

    obj.populateGlobalSeatField = function () {
        var totalSeats = 0;
        $('input[type="text"][data-af-role="ticketSeatTotal"]').each(function () {
            if ($(this).val()) {
                totalSeats += parseInt($(this).val());
            }
        });
        if (totalSeats > 0) {
            $('#seat_total').val(totalSeats);
        }
    };

    /**
     * Initialize the Calendar_AgendaTicket object
     */
    obj.init = function (subformPrefix, maxAgendaTickets, ticketLabel, removeIconClass, deleteAlertLabel) {

        this.subformPrefix = subformPrefix;
        this.maxAgendaTickets = parseInt(maxAgendaTickets);
        this.ticketLabel = ticketLabel;
        this.removeIconClass = removeIconClass;
        this.deleteAlertLabel = deleteAlertLabel;

        Calendar_AgendaTicket.initEvents();
    }
}(window, document, Calendar_AgendaTicket));


var Calendar_FrontAgendaTicket = {};

(function (window, document, obj, undefined) {
    "use strict";

    $('body').on('click', 'a.accordion-toggle', function (e) {
        $(e.target).parent().siblings('.accordion-body').on('hide', function (e) {
            e.stopPropagation();
        });
    });

    obj.elements = null;

    obj.userInfos = null;

    obj.synTxtFields = {};

    obj.ticketInscription = function () {
        $('#event-ticket_form').on('click keyup', function (e) {
            var elmt = $(e.target),
                actid = elmt.data('actid');
            if (actid === undefined) {
                return true;
            }

            switch (actid) {
                case 'checkMyTicket':
                case 'baseField':
                    obj.displayUserInfos(this, elmt);
                    break;
                default:
                    return true;
                    break;
            }
            e.stopPropagation();
        });

        var checkedTicketRow = $('[data-actid="checkMyTicket"]:checked').first();
        if (checkedTicketRow.length === 0) {
            $('[data-actid="checkMyTicket"]').first().trigger('click');
        };
    };

    obj.displayUserInfos = function (formElmt, elmtTarget) {
        if (elmtTarget.prop('readonly')) {
            if (elmtTarget.data('original') !== "undefined") {
                elmtTarget.prop('checked', elmtTarget.data('original'));
            }
            return true;
        }
        var externalSubform = $(formElmt).find('.external-attendee-subform');
        if (externalSubform.length > 0) {
            var externalSubformId = externalSubform.attr('id');
            $.each(Calendar_FrontAgendaTicket.userInfos, function (k, v) {
                if (externalSubform.find('#' + externalSubformId + '-' + k).length > 0) {
                    Calendar_FrontAgendaTicket.userInfos[k] = externalSubform.find('#' + externalSubformId + '-' + k).val();
                }
            });
        }

        $(formElmt).find('tr').each(function (index, row) {
            // treats checkbox
            var checkbox = $(row).find('input:checkbox');

            if (checkbox.length === 0) {
                return;
            }

            var isChecked = $(checkbox).prop('checked');
            // treats user name
            $(row).find('input:text').each(function (_, inpt) {
                var node = $(inpt),
                    inptName = node.data('name'),
                    val = node.val().trim();

                if (!Calendar_FrontAgendaTicket.userInfos.hasOwnProperty(inptName)) {
                    return;
                }

                if (isChecked) {
                    if (Calendar_FrontAgendaTicket.userInfos[inptName] !== undefined) {
                        node.val(Calendar_FrontAgendaTicket.userInfos[inptName])
                    }
                    node.prop('readonly', true);
                } else {
                    var dataOrigVal = node.attr('data-origval');
                    if (val !== Calendar_FrontAgendaTicket.userInfos[inptName]) {
                        node.attr('data-origval', val);
                    }

                    if (!!dataOrigVal) {
                        node.val(dataOrigVal)
                            .prop('readonly', false);
                    } else {
                        if (val === Calendar_FrontAgendaTicket.userInfos[inptName]) {
                            node.val('')
                                .prop('readonly', false);
                        }
                    }
                }
            });
        });
    };

    /**
     * Recalculate total price
     */
    obj.recalculatePrice = function() {
        var total = 0;
        var elements = obj.elements;
        if (Calendar_FrontAgendaTicket.elements != null) {
            elements = Calendar_FrontAgendaTicket.elements;
        }
        $.each(elements, function (key, value) {
            var elmtId = '#agenda_ticket_quantity_' + value,
                elmt = $(elmtId),
                nbrTickets = elmt.val(),
                price = elmt.data('ticketprice'),
                isDiscounted = !!elmt.data('ticketdiscounted');
            if (isDiscounted) {
                price = elmt.data('ticketdiscountedprice');
            }
            if (elmt.length === 1) {
                total += parseFloat(price) * parseFloat(nbrTickets);
            }
        });

        var donationPrice = $('#donation-price').val();
        if(donationPrice !== undefined) {
            if (donationPrice.trim() !== '' && !(isNaN(donationPrice))) {
                total += parseFloat(donationPrice);
            }
        }

        $('#spnTotalPrice').fadeOut(150, function () {
            var container = $('#spnTotalPrice'),
                format = container.data('price-format'),
                value = total.toFixed(2);
            if (format !== undefined) {
                value = format.replace(/%s/gi, value);
            }
            container.html(value);
        }).fadeIn(150);

        var withCoupon = !!$('input[name="coupon_code"]').length;

        // Hide / Show the block based on the total price
        if (parseFloat(total) === 0.00 && !withCoupon) {
            $('#price-container').fadeOut(150);
        } else {
            $('#price-container').fadeIn(150);
        }
    };

    /**
     * Initialize the Calendar_FrontAgendaTicket object
     */
    obj.ticketChoice = function (tagId, elementsJson) {
        Calendar_FrontAgendaTicket.elements = $.parseJSON(elementsJson);
        obj.elements = $.parseJSON(elementsJson);
        var tag = $('#' + tagId);

        $(window).bind('beforeunload', function () {
            tag.off('change', 'select');
            tag.off('change', 'input[name="coupon_code"]');
            tag.off('keyup', 'input');
        });

        tag.on('keyup', 'input', function(e) {
            obj.recalculatePrice();
        });

        tag.on('change', 'input[name="coupon_code"]', function (e) {
            var field = $(this);
            var btnId = field.closest('[data-button]').data('button');
            var successLabelId = field.closest('[data-coupon-success]').data('coupon-success');
            tag.find(successLabelId).hide();
            tag.find(btnId).show();
            tag.find('div[data-ticketprice]').each(function () {
                $(this).html($(this).data('ticketprice'))
                  .removeData('ticketprice')
                  .removeAttr('data-ticketprice');
            });
            tag.find('select[data-ticketdiscounted]')
              .removeData('ticketdiscounted')
              .removeAttr('data-ticketdiscounted');
            obj.recalculatePrice();
        });

        tag.on('change', 'select', function (e) {
            var t = $(this),
                actid = t.data('actid'),
                isContributor = t.data('ticketcontributor') === 1,
                isSubscriber = t.data('ticketsubscriber') === 1,
                switchSelectField = (isContributor || isSubscriber) && parseInt(t.val()) !== 0;

            if (actid === undefined) {
                return;
            }

            var ticketId = t.data('ticketid'),
                avSeats = t.data('ticketseats'),
                seats = avSeats - t.val(),
                seatTags = 'seatsAvail' + ticketId,
                seatTagId = '#' + seatTags;

            if (!isNaN($(seatTagId).html())) {
                $(seatTagId).fadeOut(150, function () {
                    $(seatTagId).html(seats);
                }).fadeIn(150);
            }

            var elements = obj.elements;
            if (Calendar_FrontAgendaTicket.elements != null) {
                elements = Calendar_FrontAgendaTicket.elements;
            }
            $.each(elements, function (key, value) {
                var elmtId = '#agenda_ticket_quantity_' + value,
                    elmt = $(elmtId);
                if (elmt.length === 1) {
                    var disableState = null;
                    // when contributor ticket, disable other contributor tickets only
                    if (elmt.data('ticketcontributor') == 1 && isContributor) {
                        disableState = (switchSelectField && elmt.attr('id') !== t.attr('id'));
                        elmt.prop('disabled', disableState);
                    }
                    if (elmt.data('ticketsubscriber') == 1 && isSubscriber) {
                        disableState = (switchSelectField && elmt.attr('id') !== t.attr('id'));
                        elmt.prop('disabled', disableState);
                    }
                }
            });
            obj.recalculatePrice();
        });
        obj.recalculatePrice();
    };
}(window, document, Calendar_FrontAgendaTicket));


var Calendar_AdminOnePageCheckout = {};

(function (window, document, obj, undefined) {
    "use strict";

    obj.template = $('#tpl-additional-guest');

    obj.guestSubformPrefix = null;

    obj.guestContainer = $('#guests');

    obj.guests = {};

    obj.updateQuantity = function () {
        $('#productlist').on('change', function (e) {
            var elmt = $(e.target),
                actid = elmt.data('actid');
            if (actid === undefined) {
                return true;
            }

            switch (actid) {
                case 'updateAttendeeForm':
                    obj.updateAttendeeForm(elmt);
                    break;
                default:
                    return true;
                    break;
            }
            e.stopPropagation();
        });
    };

    obj.toggleHeader = function () {
        var guestForms = $('#guests .guest-row').length;
        if (guestForms > 0) {
            $('.additional-guests').fadeIn().show();
        } else {
            $('.additional-guests').fadeOut().hide();
        }
    };

    obj.initTemplate = function () {
        $.each(obj.guests, function (itemId, data) {
            var trRootNodeName = obj.createGuestTr(itemId),
                trNode = $('#' + trRootNodeName);
            $.each(data, function (key, value) {
                var nodeHtml = obj.createGuestHtmlNode(itemId, key),
                    jNode = $(nodeHtml),
                    personalTicket = (parseInt(value.personal_ticket) === 1);
                jNode.find('.firstname').val(value.firstname);
                jNode.find('.lastname').val(value.lastname);
                jNode.find('.email').val(value.email);
                jNode.find('.personal_ticket').attr('checked', personalTicket);

                var elements = ['firstname', 'lastname', 'email'];
                for (var key in elements) {
                    var errorNode = jNode.find('.' + elements[key] + '-error');
                    if (value.errors === undefined || value.errors[elements[key]] === undefined) {
                        errorNode.remove();
                    } else {
                        jNode.find('.' + elements[key]).addClass('error');
                        errorNode.find('.text-error').text(value.errors[elements[key]]);
                    }
                }

                if (personalTicket) {
                    jNode.find('.firstname, .lastname, .email').prop('readonly', true);
                }

                trNode.after(jNode);
            });
        });

        if (Object.keys(obj.guests).length) {
            obj.toggleHeader();
            obj.updateAttendeeTableIndexes();
        }
    };

    obj.updateAttendeeForm = function (elmt) {
        var itemId = elmt.data('itemid'),
            qtt = parseInt(elmt.val()),
            ticketName = $('#productconfig_rsvp_' + itemId + '_label').html(),
            trRootNodeName = obj.createGuestTr(itemId),
            trNode = $('#' + trRootNodeName),
            nextTrRootNodeName = trNode.next('.guest-collapsed-tr'),
            nodes = $('tr.' + itemId),
            totalNodes = nodes.length,
            maxNode = Math.max(totalNodes, qtt);

        for (var i = 0; i < maxNode; i++) {
            if (i >= qtt) {
                $(nodes[i]).remove();
            } else if (!nodes[i]) {

                var nodeHtml = obj.createGuestHtmlNode(itemId, i);
                if (nextTrRootNodeName.length === 0) {
                    trNode.after(nodeHtml);
                } else {
                    nextTrRootNodeName.before(nodeHtml);
                }
            }
        }
        obj.toggleHeader();
        obj.updateAttendeeTableIndexes();

        var checkedTicketRow = $('#guests [data-actid="personalTicket"]:checked').first();
        if (checkedTicketRow.length === 0) {
            $('#guests [data-actid="personalTicket"]').first().trigger('click');
        };
    };

    obj.updateAttendeeTableIndexes = function () {
        var guestsContainer = $('#guests'),
            i = 1;
        guestsContainer.find('.guest-row').each(function () {
            $(this).find('.index').text(i);
            i++;
        });
    };

    obj.ticketInscription = function () {
        $('#onepagecheckout-form').on('click keyup change', function (e) {
            var elmt = $(e.target),
                actid = elmt.data('actid');
            if (actid === undefined) {
                return true;
            }
            switch (actid) {
                case 'personalTicket':
                case 'shippingFirstname':
                case 'shippingLastname':
                case 'shippingEmail':
                    Calendar_AdminOnePageCheckout.displayUserInfos(this, elmt);
                    break;
                default:
                    return true;
                    break;
            }
            e.stopPropagation();
        });
    };

    obj.displayUserInfos = function (formElmt, elmtTarget) {
        var shippingSubform = $(formElmt).find('#shipping-block'),
            userInfos = {
                'firstname': shippingSubform.find('#shipping_firstname').val(),
                'lastname': shippingSubform.find('#shipping_lastname').val(),
                'email': shippingSubform.find('#shipping_email').val(),
            };

        $(formElmt).find('tr.guest-row').each(function (index, row) {
            // treats checkbox
            var checkbox = $(row).find('input:checkbox');

            if (checkbox.length === 0) {
                return;
            }

            var isChecked = $(checkbox).prop('checked');
            // treats user name
            $(row).find('input:text').each(function (_, inpt) {
                var node = $(inpt),
                    inptName = node.data('name'),
                    val = node.val().trim();

                if (!userInfos.hasOwnProperty(inptName)) {
                    return;
                }

                if (isChecked) {
                    if (userInfos[inptName] !== undefined && userInfos[inptName].length > 0) {
                        node.val(userInfos[inptName]);
                        node.prop('readonly', true);
                    }
                } else {
                    node.prop('readonly', false);
                }
            });
        });
    };

    obj.createGuestTr = function (nutshell) {
        var trRootNodeName = 'guest-' + nutshell + '-rsvp';
        if (!$('#' + nutshell).length) {
            $('<tr>', {
                id: trRootNodeName,
                class: 'guest-collapsed-tr'
            }).appendTo('#guests');
        }
        return trRootNodeName;
    };

    obj.getGuestsTemplate = function () {
        if (Calendar_AdminOnePageCheckout.template.length === 0) {
            Calendar_AdminOnePageCheckout.template = $('#tpl-additional-guest');
        }
        return Calendar_AdminOnePageCheckout.template;
    };

    obj.createGuestHtmlNode = function (itemId, index) {
        var guestTemplate = obj.getGuestsTemplate(),
            node = guestTemplate.clone();
        node = node.find('tbody');
        $(node).find('[data-af-role="label"]').html(
            Ecommerce_OnePageCheckout.quoteItems[itemId].initialConfig.title
        );
        var nodeHtml = node.show().html();
        nodeHtml = nodeHtml.replace(/{ticketId}/g, itemId);
        nodeHtml = nodeHtml.replace(/{guestId}/g, index);
        return nodeHtml;
    };

    obj.init = function (guestSubformPrefix) {

        Calendar_AdminOnePageCheckout.guestSubformPrefix = guestSubformPrefix;

        $('#shipping_firstname').attr('data-actid', 'shippingFirstname').attr('disabled', false);
        $('#shipping_lastname').attr('data-actid', 'shippingLastname').attr('disabled', false);
        $('#shipping_email').attr('data-actid', 'shippingEmail');
        $('#product_type').val(Ecommerce_OnePageCheckout.mainProduct.id)
    };

}(window, document, Calendar_AdminOnePageCheckout));

var Calendar_AgendaTimer = {};

(function (window, document, obj, undefined) {
    "use strict";

    obj.notificationText = '';
    obj.cancelNotificationText = '';

    obj.startTimestamp = null;
    obj.limitTimer = null;
    obj.timerText = '';

    obj.endTimeLimit = null;
    obj.endSecondsRemains = 0;
    obj.duration = null;

    obj.notificationOptions = {};
    obj.notification = null;

    obj.event = null;
    obj.groupContext = 0;
    obj.timerId = null;

    /**
     *
     * @param options
     */
    obj.setNotificationOptions = function (options) {

        var notyText = options.notyText,
            buttonsText = options.buttonsText,
            eventUrl = options.eventUrl,
            currentMoment = moment(),
            newSecondsRemains = obj.endTimeLimit.diff(currentMoment, 'second'),
            newEndDate = moment.duration(newSecondsRemains, 'second'),
            onShow = options.onShow,
            notificationText = obj.getNewNotificationText(newEndDate);


        if (obj.endSecondsRemains <= 120) {
            var type = 'error';
        } else {
            var type = 'warning';
        }

        obj.notificationOptions = {
            text: notificationText,
            theme: 'af',
            layout: 'afBottomLeft',
            type: type,
            maxVisible: 1,
            force: false,
            killer: true,
            callback : {
              onShow: onShow
            },
            closeWith: ['button'],
            buttons: [

                {
                    addClass: 'btn',
                    text: buttonsText.cancel,
                    onClick: function ($noty) {
                        $noty.close();
                        var cancelLink = $('#event-ticket-container').find('#form_cancel');
                        if (cancelLink.length > 0) {
                            $(cancelLink.get(0)).trigger('click');
                            obj.closeNotification(obj.event.id);

                            noty({
                                theme: 'af',
                                layout : "afBottomLeft",
                                text: obj.cancelNotificationText,
                                type: 'success',
                                timeout: 5000
                            });

                        } else {
                            var groupParam = '';
                            if (obj.event.groupId !== 0 && obj.groupContext === 1) {
                                groupParam = '&group_id=' + obj.event.groupId;
                            }
                            var cancelCartPl = new PostLink({
                                id: 'cancelAttendee' + obj.event.id,
                                url: '/taglib/sectionupdate/update?updatelist=cancelCartSection:action://calendar/agenda-ticket/cancel-cart',
                                staticparams: 'event_id=' + obj.event.id + groupParam,
                                onsuccess: function (response) {
                                    obj.closeNotification(obj.event.id);

                                    var responseObj = $.parseJSON(response.responseText),
                                        contentObj = $.parseJSON(responseObj.cancelCartSection);

                                    if (contentObj.error === true) {
                                        var type = 'error';
                                    } else {
                                        var type = 'success';
                                    }
                                    noty({
                                        theme: 'af',
                                        layout: 'afBottomleft',
                                        text: contentObj.message,
                                        type: type,
                                        timeout: 5000
                                    });
                                }
                            });
                            cancelCartPl.doPost();
                        }
                    }
                },
                {
                    addClass: 'btn',
                    text: buttonsText.validate,
                    onClick: function ($noty) {
                        var redirectToEventPl = null;
                        if (obj.event.groupId !== 0 && obj.groupContext === 1) {
                            redirectToEventPl = new PostLink({
                                id: 'redirectToEvent' + obj.event,
                                url: '/taglib/sectionupdate/update?updatelist=content:action://group/index/show',
                                staticparams: 'id=' + obj.event.groupId + '&tab=calendar&event_id=' + obj.event.id,
                                updateHashParam: true
                            });

                        } else {
                            redirectToEventPl = new PostLink({
                                id: 'redirectToEvent' + obj.event,
                                url: '/taglib/sectionupdate/update?updatelist=content:action://calendar/index/show',
                                staticparams: 'id=' + obj.event.id,
                                updateHashParam: true
                            });
                        }
                        redirectToEventPl.setHistoryEntry(obj.eventUrl);
                        redirectToEventPl.setScrollTo('event-ticket-container');
                        redirectToEventPl.doPost();
                    }
                }
            ]
        };
    };

    /**
     *
     * @param date
     * @returns {string}
     */
    obj.getNewNotificationText = function (date) {
        var minutes = date.minutes(),
            seconds = date.seconds(),
            timerString = obj.timerText,
            notificationText = obj.notificationText;

        if (minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds <= 9) {
            seconds = "0" + seconds;
        }

        timerString = timerString.replace('{minutes}', minutes).replace('{seconds}', seconds);

        return notificationText.replace('{timer}', timerString).replace('{timerMobile}', timerString);
    };

    /**
     * Change the noty text
     */
    obj.updateNotificationText = function () {
        var currentMoment = moment(),
            newSecondsRemains = obj.endTimeLimit.diff(currentMoment, 'second'),
            newEndDate = moment.duration(newSecondsRemains, 'second'),
            notificationText = obj.getNewNotificationText(newEndDate);

        obj.notification.setText(notificationText);
        if (obj.endSecondsRemains == 120) {

            // Removes previous noty-type-x class to avoid conflicts of CSS
            var findLi = $("li");
            var notiId = $('#noty_afBottomLeft_layout_container');
            notiId.find(findLi)
                .first()
                .removeClass(
                    function (index, className) {
                        return (className.match(/\bnoty-type-\S+/g) || []).join(' ');
                    }
                );
            obj.notification.setType('error');
        }
        obj.endSecondsRemains = newSecondsRemains;
    };

    /**
     * trigger the timeout : recursive call
     */
    obj.agendaTimeout = function () {
        if (obj.endSecondsRemains > 0) {
            obj.updateNotificationText();
            obj.timerId = setTimeout(obj.agendaTimeout, 1000);
        } else {
            var notyId = $('body').data('noty-event-' + obj.event.id);
            obj.closeNotification(obj.event.id);
            clearTimeout(obj.timerId);
            obj.timerId = null;
            obj.notification = null;

            if (notyId !== undefined) {
                var cancelCartPl = new PostLink({
                    id: 'cancelAttendee' + obj.event.id,
                    url: '/taglib/sectionupdate/update?updatelist=cancelCartSection:action://calendar/agenda-ticket/cancel-cart',
                    staticparams: 'event_id=' + obj.event.id + '&expired=true',
                    loader: false,
                    onsuccess: function (response) {

                        var responseObj = $.parseJSON(response.responseText),
                            contentObj = $.parseJSON(responseObj.cancelCartSection);

                        if (contentObj.error === true) {
                            var type = 'error';
                        } else {
                            var type = 'success';
                        }
                        noty({
                            theme: 'af',
                            layout:'afBottomLeft',
                            text: contentObj.message,
                            type: type,
                            timeout: 15000
                        });

                        var cancelLink = $('#event-ticket-container').find('#form_cancel');
                        if (cancelLink.length > 0) {
                            var forwardToStep1Pl = new PostLink({
                                id: 'cancelAttendee' + obj.event.id,
                                url: '/taglib/sectionupdate/update?updatelist=event-ticket-container:action://calendar/agenda-ticket/index',
                                staticparams: 'event_id=' + obj.event.id,
                                loader: false
                            });
                            forwardToStep1Pl.doPost();
                        }
                    }
                });
                cancelCartPl.doPost();
            }
        }
    };

    /**
     *
     * @param eventId
     * @returns {boolean}
     */
    obj.closeNotification = function (eventId) {
        var notyId = $('body').data('noty-event-' + eventId);
        if (notyId !== undefined) {
            $.noty.close(notyId);
            $('body').removeData('noty-event-' + eventId);
            clearTimeout(obj.timerId);
            obj.timerId = null;
        }
        return notyId !== undefined;
    };

    /**
     *
     * @param eventId
     * @param options
     */
    obj.successNotification = function (eventId, options) {
        var close = obj.closeNotification(eventId);
        if (close) {
            noty({
                theme: 'af',
                layout:'afBottomLeft',
                text: options.text,
                type: options.type,
                timeout: 10000
            });
        }
    };

    /**
     *
     * @param options
     */
    obj.init = function (options) {
        var notificationText = options.notyText,
            currentDate = moment();
        obj.limitTimer = options.limitTimer;
        obj.timerText = options.timerText;
        obj.startTimestamp = options.startTimestamp;
        obj.event = options.event;
        obj.eventUrl = options.eventUrl;
        obj.groupContext = options.groupContext;
        obj.notificationText = notificationText;
        obj.cancelNotificationText = options.cancelNotificationText;

        obj.endTimeLimit = moment.unix(obj.startTimestamp).add(obj.limitTimer, 'seconds');
        obj.endSecondsRemains = obj.endTimeLimit.diff(currentDate, 'second');
        obj.onShow = options.onShow;

        obj.setNotificationOptions(options);
        if ($('body').data('noty-event-' + obj.event.id) === undefined) {
            obj.notification = Mevia_Notification.addNotification(obj.notificationOptions);
            var bodyData = $('body').data();
            $.each(bodyData, function (k, v) {
                if (/notyEvent/i.test(k)) {
                    $.noty.close(v);
                }
            });

            $('body').data('noty-event-' + obj.event.id, obj.notification.options.id);
            obj.agendaTimeout();
        }
    };

}(window, document, Calendar_AgendaTimer));

Calendar_ExternalFields = {};
(function (window, document, obj, undefined) {
    "use strict";

    obj.icon = '<i class="af-font-icon-checkbox-ok font-inactive bigger"></i>';
    obj.addressFields = ['address', 'zipcode', 'city'];

    obj.displayExternalField = function (elmt) {
        var elmtValue = elmt.data('value');
        if (!elmt.is(':checked')) {
            jQuery('#required_external_field_' + elmtValue).attr('checked', false);
        }
    };

    obj.requiredExternalField = function (elmt) {
        var elmtValue = elmt.data('value');
        if (elmt.is(':checked')) {
            jQuery('#display_external_field_' + elmtValue).prop('checked', true);
        }
    };

    obj.checkDefaultExternalFields = function (elmt) {
        $.each(obj.addressFields, function (key, value) {
            var addressFieldElmt = $('input[data-af-fieldname="' + value + '"]');
            if (elmt.is(':checked')) {
                addressFieldElmt.prop('checked', true).addClass('hide').after(obj.icon);
            } else {
                var defaultValue = elmt.data('af-default');
                addressFieldElmt.prop('checked', defaultValue).removeClass('hide');
                addressFieldElmt.siblings('i').remove();
            }
        });
    }
}(window, document, Calendar_ExternalFields));

Calendar_AgendaOptions = {

    /**
     * trigger Event when the user clicks on a specific checkbox : display / hide options with a transition
     */
    couldRsvpTriggerTransition: function (element) {
        var elementIsChecked = element.is(':checked'),
            elementId = element.data('af-role'),
            elementContainer = jQuery('div[data-af-target="' + elementId + '"]');
        if (elementIsChecked) {
            elementContainer.slideDown();
        } else {
            elementContainer.slideUp();
        }
    },

    /**
     * trigger Event when the user clicks on a specific checkbox : display / hide options
     */
    couldRsvpTrigger: function (element) {
        var elementIsChecked = element.is(':checked'),
            elementId = element.data('af-role'),
            elementContainer = jQuery('div[data-af-target="' + elementId + '"]');
        if (elementIsChecked) {
            elementContainer.show();
        } else {
            elementContainer.hide();
        }
    },

    /**
     * Initialize events
     */
    initEvents: function () {
        Calendar_AgendaOptions.couldRsvpTrigger(jQuery('#could_rsvp'));
    },

    /**
     * Initialize the Calendar_AgendaOptions object
     */
    init: function () {
        Calendar_AgendaOptions.initEvents();
        if (window.Calendar_AgendaOptions.initRegisterEvents === undefined) {
            Calendar_AgendaOptions.registerEvents();
            window.Calendar_AgendaOptions.initRegisterEvents = true;
        }
    }
};

var Calendar_Form_Status = {};

(function (window, document, obj, undefined) {
    "use strict";

    obj.statuses = [];
    obj.tab = null;
    obj.deletedStatus = null;
    obj.confirmText = '';
    obj.hasEventId = false;
    obj.contentChanged = false;
    obj.userIsAdmin = false;
    obj.newslettersAreUpdatable = false;

    obj.switchTab = function(elmt) {
        var status = jQuery('#status').val(),
            elmtId = elmt.attr('id'),
            postformName = '',
            postfom = null;
        if (status == obj.deletedStatus) {
            switch(elmtId) {
                case 'event_details':
                    postformName = 'event_tab_details';
                    break;
                case 'event_pictures':
                    postformName = 'event_tab_pictures';
                    break;
                case 'event_files':
                    postformName = 'event_tab_files';
                    break;
                case 'event_options':
                    postformName = 'event_tab_options';
                    break;
            }
            if (postformName !== '') {
                postfom = getCustomTag(postformName+'_form');
                if (postfom instanceof PostForm) {
                    postfom.cancelRequest();
                    obj.triggerButtons(status);
                }
            }
        }
    };
    obj.triggerButtons = function (status) {
        if (status == obj.deletedStatus) {
            if (obj.hasEventId) {
                if (confirm(obj.confirmText)) {
                    getCustomTag('delete_event').doPost();
                } else {
                    return false;
                }
            } else {
                getCustomTag('return_lk').doPost();
            }
        } else {
            var postForm = null;
            if (obj.tab == "options") {
                postForm = getCustomTag('event_tab_options_form');
            } else {
                postForm = getCustomTag('event_tab_details_form');
            }
            if (status !== obj.initialStatus || parseInt(obj.initialStatus) === 4) {
                postForm.setStaticParam('changeStatus', 1);
            }

            if (obj.contentChanged && obj.userIsAdmin && obj.newslettersAreUpdatable) {
                // setStaticParam is too crappy to manage ampersand on all case, have to escape it manually
                postForm.setStaticParam('description_for_newsletter', $('#description').froalaEditor('mailStyle.get').replaceAll('&', '%26'));

                new window.duDialog(
                    window.i18n.t('agenda.publishing.occurrence-update-newsletter-modal-title'),
                    window.i18n.t('agenda.publishing.occurrence-update-newsletter-modal-body', {
                        lang: $('#lang :selected').text().toLowerCase()
                    }),
                    {
                        buttons: window.duDialog.YES_NO_CANCEL,
                        yesText: window.i18n.t('agenda.publishing.occurrence-update-newsletter-modal-update'),
                        noText: window.i18n.t('agenda.publishing.occurrence-update-newsletter-modal-do-no-update'),
                        cancelText: window.i18n.t('common.confirmation-dialog-button-cancel'),
                        callbacks: {
                            yesClick: function() {
                                $('#update_newsletter').val('1');
                                postForm.postForm();
                                obj.contentChanged = false;
                                this.hide();
                            },
                            noClick: function() {
                                $('#update_newsletter').val('0');
                                postForm.postForm();
                                obj.contentChanged = false;
                                this.hide();
                            }
                        }
                    }
                );
            } else {
                postForm.postForm();
            }
        }
    };

    obj.initEvents = function () {
        jQuery('a#cancel_new_event').click(function () {
            getCustomTag('return_lk').doPost();
        });

        // detect when click on submit button
        jQuery('#header_status_button').off('click').on('click', function () {
            var status = jQuery('#header_status').val();
            obj.triggerButtons(status);
        });

        // detect when click on submit button
        jQuery('#status_button').off('click').on('click', function () {
            var status = jQuery('#status').val();
            obj.triggerButtons(status);
        });

        jQuery('a[data-role="status"]').click(function () {
            var value = jQuery(this).data('value');
            jQuery('#status').val(value);
            jQuery('#header_status').val(value);
            jQuery('.select-btn').find('[data-toggle="dropdown"] .status-label').each(function () {
                jQuery(this).text(obj.statuses[value]);
            });
        });

        jQuery('#description').on('froalaEditor.contentChanged', function () {
            obj.contentChanged = true;
        });
    };

    obj.init = function (options) {
        obj.statuses = options.statuses != null ? options.statuses : obj.statuses;
        obj.tab = options.tab != null ? options.tab : obj.tab;
        obj.deletedStatus = options.deletedStatus != null ? options.deletedStatus : obj.deletedStatus;
        obj.confirmText = options.confirmText != null ? options.confirmText : obj.confirmText;
        obj.hasEventId = options.hasEventId != null ? options.hasEventId : obj.hasEventId;
        obj.userIsAdmin = options.userIsAdmin != null ? options.userIsAdmin : obj.userIsAdmin;
        obj.newslettersAreUpdatable = options.newslettersAreUpdatable != null ? options.newslettersAreUpdatable : obj.newslettersAreUpdatable;

        obj.initialStatus = jQuery('#status').val();
        obj.initEvents();
    };
}(window, document, Calendar_Form_Status));
