/* Minification failed. Returning unminified contents.
(244,33-34): run-time error JS1100: Expected ',': =
(244,37-38): run-time error JS1002: Syntax error: ,
(244,57-58): run-time error JS1100: Expected ',': =
(244,61-62): run-time error JS1002: Syntax error: ,
(244,80-81): run-time error JS1100: Expected ',': =
(309,21-22): run-time error JS1003: Expected ':': (
(309,31-32): run-time error JS1100: Expected ',': {
(311,5-6): run-time error JS1002: Syntax error: }
(316,5-6): run-time error JS1002: Syntax error: }
(319,33-34): run-time error JS1004: Expected ';': {
(399,5-25): run-time error JS1018: 'return' statement outside of function: return multiDropdown
 */
var language;
var country;
var cotizar;
var selectedItemsValues = undefined;

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}


 
$(function () {
    main.init();
});

var main = {
    props: {
        language: "en",
        country: "jm",
        cotizar: "Quoting..."
    },
    //para el chat
    modoDebug: false,
    debug: function (titulo, msg) { //para el chat
        if (main.modoDebug)
            console.log(titulo + ' --> ' + msg);
    },//fin para el chat
    cargando: "Loading"
    ,
    init: function () {
         
        $.ajaxSetup({ 
            beforeSend: function (xhr, settings) {

                let contextid = getUrlVars()['contextid'];

                if (contextid == null) {
                    let hContextId = document.getElementById("hContextId");
                    if (hContextId) {
                        contextid = hContextId.value; 
                    } 
                }

                if (settings.url.indexOf('?') > -1) {
                    if (settings.url.indexOf('contextid') < 0) {
                        settings.url = settings.url + '&contextid=' + contextid;
                    }
                } else {
                    settings.url = settings.url + '?contextid=' + contextid;
                }
            }
        });


        this.props.language = $("#hfUICulture").val();

        //console.log($("#hfUICulture").val());

        this.props.country = $("#hfUICountry").val();
        if (this.props.language == "es") {
            this.props.cotizar = "Cotizando...";
            this.cargando = "Cargando...";
        }
        if (this.props.language == "pt") {
            this.props.cotizar = "Buscando...";
            this.cargando = "Carregando...";
        }

        this.bindElements();

        Parsley.addMessages('es', {
            defaultMessage: "Este campo parece ser inválido.",
            type: {
                email: "Este campo debe ser un correo válido.",
                url: "Este campo debe ser una URL válida.",
                number: "Este campo debe ser un número válido.",
                integer: "Este campo debe ser un número válido.",
                digits: "Este campo debe ser un dígito válido.",
                alphanum: "Este campo debe ser alfanumérico."
            },
            notblank: "Este campo no debe estar en blanco.",
            required: "Este campo es requerido.",
            pattern: "Este campo es incorrecto.",
            min: "Este campo no debe ser menor que %s.",
            max: "Este campo no debe ser mayor que %s.",
            range: "Este campo debe estar entre %s y %s.",
            minlength: "Este campo es muy corto. La longitud mínima es de %s caracteres.",
            maxlength: "Este campo es muy largo. La longitud máxima es de %s caracteres.",
            length: "La longitud de este campo debe estar entre %s y %s caracteres.",
            mincheck: "Debe seleccionar al menos %s opciones.",
            maxcheck: "Debe seleccionar %s opciones o menos.",
            check: "Debe seleccionar entre %s y %s opciones.",
            equalto: "Este campo debe ser idéntico."
        });

        Parsley.setLocale('es');

        $(".cross").hide();
        $(".menu").hide();
        $(".hamburger").click(function (e) {
            $(".menu").filter(':not(:animated)').slideToggle("fast");
            e.preventDefault();
        });

        $('.btn-tooltip').on('click', function () {
            return false;
        })

        $(document).ready(function () {

            if ($('.center.slider').length > 0) {
                $('.center.slider').not('.slick-initialized').slick({
                    centerMode: true,
                    centerPadding: '30px',
                    slidesToShow: $("#hfSlidesToShow").val(),
                    dots: true,
                    arrows: false
                });
            }
            $('.btn-tooltip').on('click', function () {
                return false;
            })

            if (!$('.btn-tooltip').hasClass("tooltipstered")) {
                $('.btn-tooltip').tooltipster({
                    animation: 'fade'
                });
            }

        });

        var paises = ["Afganistán", "Albania", "Alemania", "Andorra", "Angola", "Antigua y Barbuda", "Arabia Saudita", "Argelia", "Argentina", "Armenia", "Australia", "Austria", "Azerbaiyán", "Bahamas", "Bangladés", "Barbados", "Baréin", "Bélgica", "Belice", "Benín", "Bielorrusia", "Birmania", "Bolivia", "Bosnia y Herzegovina", "Botsuana", "Brasil", "Brunéi", "Bulgaria", "Burkina Faso", "Burundi", "Bután", "Cabo Verde", "Camboya", "Camerún", "Canadá", "Catar", "Chad", "Chile", "China", "Chipre", "Ciudad del Vaticano", "Colombia", "Comoras", "Corea del Norte", "Corea del Sur", "Costa de Marfil", "Costa Rica", "Croacia", "Cuba", "Dinamarca", "Dominica", "Ecuador", "Egipto", "El Salvador", "Emiratos Árabes Unidos", "Eritrea", "Eslovaquia", "Eslovenia", "España", "Estados Unidos", "Estonia", "Etiopía", "Filipinas", "Finlandia", "Fiyi", "Francia", "Gabón", "Gambia", "Georgia", "Ghana", "Granada", "Grecia", "Guatemala", "Guyana", "Guinea", "Guinea ecuatorial", "Guinea-Bisáu", "Haití", "Honduras", "Hungría", "India", "Indonesia", "Irak", "Irán", "Irlanda", "Islandia", "Islas Marshall", "Islas Salomón", "Israel", "Italia", "Jamaica", "Japón", "Jordania", "Kazajistán", "Kenia", "Kirguistán", "Kiribati", "Kuwait", "Laos", "Lesoto", "Letonia", "Líbano", "Liberia", "Libia", "Liechtenstein", "Lituania", "Luxemburgo", "Madagascar", "Malasia", "Malaui", "Maldivas", "Malí", "Malta", "Marruecos", "Mauricio", "Mauritania", "México", "Micronesia", "Moldavia", "Mónaco", "Mongolia", "Montenegro", "Mozambique", "Namibia", "Nauru", "Nepal", "Nicaragua", "Níger", "Nigeria", "Noruega", "Nueva Zelanda", "Omán", "Países Bajos", "Pakistán", "Palaos", "Panamá", "Papúa Nueva Guinea", "Paraguay", "Perú", "Polonia", "Portugal", "Reino Unido", "República Centroafricana", "República Checa", "República de Macedonia", "República del Congo", "República Democrática del Congo", "República Dominicana", "República Sudafricana", "Ruanda", "Rumanía", "Rusia", "Samoa", "San Cristóbal y Nieves", "San Marino", "San Vicente y las Granadinas", "Santa Lucía", "Santo Tomé y Príncipe", "Senegal", "Serbia", "Seychelles", "Sierra Leona", "Singapur", "Siria", "Somalia", "Sri Lanka", "Suazilandia", "Sudán", "Sudán del Sur", "Suecia", "Suiza", "Surinam", "Tailandia", "Tanzania", "Tayikistán", "Timor Oriental", "Togo", "Tonga", "Trinidad y Tobago", "Túnez", "Turkmenistán", "Turquía", "Tuvalu", "Ucrania", "Uganda", "Uruguay", "Uzbekistán", "Vanuatu", "Venezuela", "Vietnam", "Yemen", "Yibuti", "Zambia", "Zimbabue"];
        $(".paises").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/ListCountries",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.label,
                                value: item.label,
                                id: item.value
                            };
                        }));
                    }
                })
            },
            select: function (event, ui) {
                $("#IdDestination").val(ui.item.id);
                return false;
            },

        });

        if ($("#BackgroundSlider").length > 0) {
            var bodyWidth = document.body.clientWidth;
            $(".jumbotron.background").css("width", bodyWidth);

            var _SlideshowTransitions = [{
                $Duration: 1000, x: 4, $Zoom: 11, $SlideOut: true, $Easing: { $Left: $JssorEasing$.$EaseInExpo, $Zoom: $JssorEasing$.$EaseInExpo, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2
            }];

            var options = {
                $AutoPlay: true,
                $SlideWidth: bodyWidth,
                $SlideshowOptions: {
                    $Class: $JssorSlideshowRunner$,
                    $Transitions: _SlideshowTransitions,
                    $TransitionsOrder: 1,
                    $ShowLink: true
                }
            };
            var jssor_slider1 = new $JssorSlider$('BackgroundSlider', options);
        }

        if ($("#BannerSlider").length > 0) {

            var jssor_1_options = {
                $AutoPlay: true,
                $AutoPlaySteps: 1,
                $SlideDuration: 160,
                $SlideWidth: 737,
                $SlideSpacing: 1,
                $Cols: 1,
            };

            var jssor_1_slider = new $JssorSlider$("BannerSlider", jssor_1_options);

        }

        $(window).resize(function () {
            if ($("#BackgroundSlider").length > 0) {
                if ($(window).width() > 767) {
                    var bodyWidth = document.body.clientWidth;
                    $(".jumbotron.background").css("width", bodyWidth);
                    $("[data-id=img-container]").css("width", bodyWidth)
                    $("[data-u=image]").css("width", bodyWidth)
                } else {

                }
            }
        });

    },
    bindElements: function () {
        $(".ac-ui.menu").on("click", function () {
            if ($(".main-wrapper").hasClass("open")) {
                main.mainMenu.close();
            } else {
                main.mainMenu.open();
            }
            return false;
        });
        // TODO: hacer esto bien y bindear/unbindear on click de ".ac-ui.menu"
        $(".main-wrapper").on("click", function () {
            if ($(".main-wrapper").hasClass("open")) {
                main.mainMenu.close();
            }
        });
        language = $("#hfUICulture").val();
        country = $("#hfUICountry").val();

        $("li[data-country-code]").on("click", function (e) {
            main.agencySelCountry(this);
            e.stopPropagation();
            return;
        });

        $("#showPopup, .modal-background").on("click", function () {
            $(".modal-content, .modal-background").toggleClass("active");
        });
    },
    globalLoader: {
        show: function (message = '', globalLoaderTitle = '', globalLoaderText = '') {
            $("#globalLoader").show();
            $('body').addClass("globalLoaderShow");
            $("#globalLoaderTitle").html(globalLoaderTitle);
            $("#globalLoaderText").html(globalLoaderText);
            if (typeof (message) != "undefined") {
                $("#globalLoader .message").html(message);
            }
        },
        hide: function () {
            $("#globalLoader").hide();
            $('body').removeClass("globalLoaderShow");
            $("#globalLoader .message").html('');
            $("#globalLoaderTitle").html('');
            $("#globalLoaderText").html('');
        }
    },
    logger: function (msg) {
        if (console != undefined)
            console.log(msg);
        else
            alert(msg);
    },
    agencySelCountry: function (liCountrySel) {
        $('input[data-id=btnSelCountry]').CommandArgument = $(liCountrySel).attr("data-country-code");
        $('input[data-id=btnSelCountry]').click();
    },
    modoDebug: true,
    debug: function (titulo, msg) { //para el chat
        if (main.modoDebug)
            console.log(titulo + ' --> ' + msg);
    },
    redirectPopup: function (path) {
        if (path === null || path == undefined || path === "") {
            document.location.pathname = $("#countrySource").html();
        }
        else {
            document.location.search = path;
        }
    },
    redirectLanding: function () {
        var iso2code = document.location.pathname;
        document.location.href = iso2code + "/promosbancarias";
    },
    context: {
        getId: function () {
            let htmlTag = document.getElementsByTagName("HTML")[0];
            let contextid = htmlTag.getAttribute('contextid');
            if (!contextid) {
                contextid = getUrlVars()['contextid'];
            }
            return contextid;
        },
        addContextToUrl: function (url) {
            let htmlTag = document.getElementsByTagName("HTML")[0];
            let contextid = htmlTag.getAttribute('contextid');
          
            if (!contextid) {
               contextid = getUrlVars()['contextid'];
            }

            return url + '?contextid=' + contextid;
        }
    },

    logclickDetailGA(product) {
        myAcAnalytics.pushJson('{"event":"trackEvent","eventCategory":"Navegacion","eventAction":"Detalle de cobertura","eventLabel":"Ver detalle de ' + product + '"}');
    },

    logEventDetalle(pais, producto, origen) {
        var track = '{"event":"user_interaction","Pais":"' + pais + '","eventLabel":"Ver detalle de ' + producto + '","origen_cotizacion":"' + origen + '"}';
        myAcAnalytics.pushJson(track);
    }
};

function MultiDropDownControl() {
    var multiDropdown = {
        controller: "",
        availableValues: [],
        fnGetSelectedItems: function () { return null },
        fnSelItem: function (itemSel) { },
        bSeleccionarOk: function () { return true; },
        split: function (val) {
            return val.split(/,\s*/);
        },
        extractLast: function (term) {
            console.log(term.toLowerCase());
            return $.grep(multiDropdown.availableValues, function (e) { return e.label.toLowerCase().indexOf(term.toLowerCase()) >= 0; });
        },
        InitSelectedItems: function () {
            if (selectedItemsValues == undefined) {
                selectedItemsValues = multiDropdown.fnGetSelectedItems();
            }
            if (selectedItemsValues.length > 0) {
                $(selectedItemsValues).each(function (index, item) {
                    multiDropdown.fnSelItem(item);
                });
            }
        },
        bind: function (txt) {
            $(txt)
                // don't navigate away from the field on tab when selecting an item
                .on("keydown", function (event) {
                    if (event.keyCode === $.ui.keyCode.TAB &&
                        $(this).autocomplete("instance").menu.active) {
                        event.preventDefault();
                    }
                })
                .autocomplete({
                    minLength: 0,
                    close: function () {
                        $('.ui-menu').css('display', 'block');
                    },
                    source: function (request, response) {
                        $.ajax({
                            url: multiDropdown.controller,
                            type: "POST",
                            dataType: "json",
                            data: { term: request.term },
                            success: function (data) {
                                response($.map(data, function (item) {
                                    return {
                                        label: item.label,
                                        value: item.label,
                                        id: item.value
                                    };
                                }));
                            }
                        })
                    },
                    create: function () {
                        $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
                            var checked = ($("li[value='" + item.id + "']").length > 0 ? 'checked' : '');
                            return $("<div></div>")
                                .data("item.autocomplete", item)
                                .append('<span><input type="checkbox" ' + checked + ' chkDestino data-id="' + item.id + '"/>' + item.label + '</span>')
                                .appendTo(ul);
                        };
                    },
                    search: function () {
                        multiDropdown.extractLast(this.value);
                    },
                    select: function (event, ui) {
                        var terms = multiDropdown.split(this.value);
                        // remove the current input
                        terms.pop();
                        multiDropdown.fnSelItem(ui.item);
                        return false;
                    }
                })
                .focus(function () {
                    $(this).autocomplete("search");
                });
        }
    };
    return multiDropdown;
}

function ConfigdropdownCascading(ddOrigen) {
    var dropdownCascading = {
        controller: "",
        actionSearch: "",
        ddDestino: null,
        getFiltros: function () { },
        FiltroDataType: "Json",
        bind: function (ddOrigen) {
            $(ddOrigen).on("change", function () {
                dropdownCascading.cargarDestino();
            });
        },
        fnDestino: function () { },
        cargarDestino: function () {
            main.globalLoader.show();
            $.ajax({
                type: "POST",
                data: dropdownCascading.getFiltros(),
                url: (dropdownCascading.controller != "" ? dropdownCascading.controller + "/" : "") + dropdownCascading.actionSearch,
                dataType: dropdownCascading.FiltroDataType,
                error: function (xhr, status, error) {
                    //if (modoDebug) 
                    console.log(error);
                    //main.showErrorDiv(error);
                },
                success: function (json) {
                    if (dropdownCascading.fnDestino)
                        dropdownCascading.fnDestino(json);
                    else {
                        html = $.map(json, function (obj) {
                            return '<option value="' + obj.Id + '">' + obj.Label + '</option>'
                        }).join('');

                        $(dropdownCascading.ddDestino).html(html);
                    }
                },
                complete: function () {
                    main.globalLoader.hide();
                }
            });
        }
    };

    dropdownCascading.bind(ddOrigen);

    return dropdownCascading;
}

/* tooltip menu sidebar */

$(document).ready(function () {
    $('#info-tooltip').tooltipster({
        theme: ['tooltipster-noir', 'tooltipster-noir-customized'],
        trigger: 'custom',
        triggerOpen: {
            mouseenter: true,
            touchstart: true,
            click: true,
            tap: true
        },
        triggerClose: {
            mouseleave: true,
            originClick: true,
            touchleave: true,
            click: true,
            tap: true
        }
    });
});
;

//Primero me aseguro que haya iniciado el main
main.init();

if ($(window).width() > 767){
    $.datepicker._findPos = function (obj) {    
        var inst = $.datepicker._getInst(obj);
        var isRTL = this._get(inst, 'isRTL');

        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
            if (isRTL) {
                obj = obj.previousSibling;
            } else {
                obj = obj.nextSibling;
            }
        }

        var position = $(obj).offset();
        return [position.left, position.top];
    
    };
 
    $("#ui-datepicker-div").click(function (event) {
        event.stopPropagation();
    });
}
var txtCalendar = {

    selectedDatesCustomStyles: function (inst) {
        setTimeout(function () {
            //se quita el estilo para fecha de hoy, y se agrega el texto "hoy" debajo
            var todayTd = inst.dpDiv.find('.ui-datepicker-today');
            if (todayTd.find('.todayMessageText').length == 0) //si el texto de hoy no está agregado, lo agrego
                todayTd.append('<p class="todayMessageText">' + $('#hfTodayText').val() + '</p>');
            todayTd.find('a.ui-state-highlight').removeClass('ui-state-highlight'); //quito el estilo default de bootstrap
            var todayTextP = todayTd.find('.todayMessageText');
            var leftTodayText = ((todayTd.width() - todayTextP.width()) / 2) + 'px'; //calculo el centro de la td de hoy
            todayTextP.css('margin-left', leftTodayText);
            if (todayTextP.parent().hasClass('selectedStartDate')) //si la fecha start es hoy, cambio el color del texto hoy a blanco
                todayTextP.css('color', 'black');

            //estas 2 lineas agregan el piquito triangular a la derecha de la startdate
            $('.selectedStartDate').append('<p class="afterSelectedStartDate"></p>');
            $('.afterSelectedStartDate').css('margin-left', $('.selectedStartDate').width() + 1 + 'px');
            //estas 2 lineas agregan el piquito triangular a la izquiera de la enddate
            $('.selectedEndDate').append('<p class="beforeSelectedEndDate"></p>');
            //$('.beforeSelectedEndDate').css('margin-left', -($('.selectedEndDate').width() - 13) + 'px');
            $('.beforeSelectedEndDate').css('margin-left', '-15px');


            $('.selectedMiddleDates a, .selectedStartDate a, .selectedEndDate a').css('color', 'white');


        }, 10);
    },

    init: function (txt, fnOnSelect) {
        //Si no está definido un lenguaje se utiliza el del navegador

        if (main.props.language == "") {
            var userLang = navigator.language || navigator.userLanguage;
            userLang = userLang.substring(0, 2);
            main.props.language = userLang;
        }
        $.datepicker.setDefaults($.datepicker.regional[main.props.language]);
                
        var months = 1;

        if ($(window).width() > 767)
            months = 2;

        var isProductPageV3 = ($("body").hasClass("product-page-V3")) ? true : false;
        var dateFormatOption = "dd/mm/yy";
        if (isProductPageV3) {
            var dateFormatOption = $("#hfBusinessLang").val() === "en" ? "mm/dd/yy" : "dd/mm/yy";
        }

        $(txt).datepicker({
            numberOfMonths: months,
            yearRange: "-0:+10",
            dateFormat: dateFormatOption,
            minDate: 0,
            showButtonPanel: false,
            onSelect: function (val) {
                if (fnOnSelect != undefined)
                    fnOnSelect(val);
                if ($(quoter.startDate).val() == val)
                {
                    var miniumFromDate = $(quoter.startDate).datepicker("getDate");
                    $(quoter.endDate).datepicker("option", "minDate", miniumFromDate);
                    var maxiumToDate = new Date(miniumFromDate);
                    maxiumToDate.setDate(miniumFromDate.getDate() + 364);
                    $(quoter.endDate).datepicker("option", "maxDate", maxiumToDate);
                    setTimeout(function () { $(quoter.endDate).datepicker("show") }, 50);

                }
            },
            beforeShow: function (input, inst) {
                window.setTimeout(function () {

                    var offset = $(input).offset();
                    var height = $(input).height();
                    var left = txtCalendar.calculateDatePickerLeft(inst, offset);
                    //Seteo para ambos calendarios el top y left
                    if (offset.top > 0) {
                        inst.dpDiv.css({ top: (offset.top + height + 20) + 'px', left: (left) + 'px' });
                    }
                }, 200); //si le quitas el timeout no funca jajaj
                txtCalendar.selectedDatesCustomStyles(inst);
            },
            //onClose: function (input, inst) {
            //    $('.requoter-body').css({ overflowY: 'auto', overflowX: 'hidden' })
            //},
            
            onChangeMonthYear: function (year, month, inst) {
                txtCalendar.selectedDatesCustomStyles(inst);
            },
            beforeShowDay: function (date) {
                var dateFrom = $("#txtStartDate").datepicker('getDate');
                var dateTo = $("#txtEndDate").datepicker('getDate');

                if (date > dateFrom && date < dateTo) {
                    return [true, 'selectedMiddleDates', ''];
                }
                if (date.getTime() == dateFrom.getTime()) {
                    return [true, 'selectedStartDate', ''];
                }
                if (date.getTime() == dateTo.getTime()) {
                    return [true, 'selectedEndDate', ''];
                }
                return [true, '', ''];
            }
        });
    },
    setDate: function (txt, val, startDate) {
        if (val != '')
            $(txt).datepicker("setDate", val);
        else
            $(txt).datepicker("setDate", null);
    },
    setMaxDate: function (txt, val) {
        $(txt).datepicker("option", "endDate", val);
    },
    setMinDate: function (txt, val) {
        if (val == "") val = new Date();
        $(txt).datepicker("option", "startDate", val);
    },
    getDate: function (txt) {
        var format = $.datepicker.regional[main.props.language].dateFormat;
        return $(txt).datepicker("getDate", format);
    },
    calculateDatePickerLeft: function (inst, offset) {

        var width = $(window).width();
        var left = 0;
        if (width >= 320 && width < 768) {
            if (inst.id === 'txtEndDate') {
                left = $('.row.mt-3-custom.mobile-mt-1-custom').width() - $('#ui-datepicker-div').width() + $('.row.mt-3-custom.mobile-mt-1-custom').offset().left
            }
            else {
                left = $('.row.mt-3-custom.mobile-mt-1-custom').offset().left;
            }
        } else {
            left = offset.left;
        }
        return left;
    }
};

var txtBirthDate = {
    init: function (txt, fnOnSelect) {
        $.datepicker.setDefaults($.datepicker.regional[language]);
        $(txt).datepicker({
            changeYear: true,
            changeMonth: true,
            yearRange: "-100:+0",
            maxDate: new Date(),
            onSelect: function(val) {
                if (fnOnSelect != undefined)
                    fnOnSelect(val);
            }
        });

        $(txt).on("focusout", ".hasDatepicker", function(e) {
            var date1 = $(this).val();
            if (date1 != "") {
                var validate = isValidDate(date1);
                if (!validate) {
                    $(this).addClass("input-error");
                    $(this).val("");
                } else {
                    $(this).removeClass("input-error");
                }
            }
        });
    }
};

var txt = {
    init: function (ctrlTXT) {
        $("input[required='true']", ctrlTXT).not("[data-id='txtBirthDate']").on("blur", function (e) {
            if ($(this).val() == '') {
                // los que tienen vacios muestro error y cambio return
                $(this).addClass("input-error");
            } else {
                $(this).removeClass("input-error");
            }
        });

        $("select[data-id='ddlMonthDate']", ctrlTXT).on("blur", function (e) {
            if ($(this).find('option:selected').text() == 'MM') {
                // si no hay mes elegido, muestro error
                $(this).addClass("input-error");
            } else {
                $(this).removeClass("input-error");
            }
        });

        $("textarea[required='true']", ctrlTXT).on("blur", function (e) {
            if ($(this).val() == '') {
                // los que tienen vacios muestro error y cambio return
                $(this).addClass("input-error");
            } else {
                $(this).removeClass("input-error");
            }
        });

        $("input[data-type='email']", ctrlTXT).on("blur", function (e) {
            var esValido = false;
            var mail = $(this).val();
            if (mail == "")
                esValido = true;
            else {
                if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail))
                    esValido = true;
                else
                    esValido = false;

                if (!esValido) {
                    $(this).addClass("input-error");
                } else {
                    $(this).removeClass("input-error");
                }
            }

            return esValido;
        });

        $("input[data-type='number']", ctrlTXT).on("keypress", function (e) {
            //Solo numeros
            if (["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"].indexOf(String.fromCharCode(e.which)) == -1) {
                e.preventDefault();
            }

            if (e.which == 13) {
                submitMessage(this);
                e.preventDefault();
            }
        });
    }
};


var inputAdder = {
    init: function (onChange) {
        // inicializa por clase

        $(document).on("click", ".ac-ui.input-adder .add, .ac-ui.input-adder .remove", onChange);

        $(document).on("click", ".ac-ui.input-adder .add", function () {
            var inp = $(this).siblings("input");
            $(inp).val(parseInt($(inp).val(), 10) + 1);
        });

        $(document).on("click", ".ac-ui.input-adder .remove", function () {
            var inp = $(this).siblings("input");
            $(inp).val(parseInt($(inp).val(), 10) - 1);
        });

        

    }
};;
