/* Minification failed. Returning unminified contents.
(1284,24-25): run-time error JS1195: Expected expression: >
(1297,6-7): run-time error JS1195: Expected expression: )
(1403,30-31): run-time error JS1195: Expected expression: .
(1452,12-13): run-time error JS1014: Invalid character: `
(1452,14-15): run-time error JS1004: Expected ';': {
(1452,27-28): run-time error JS1004: Expected ';': $
(1452,33-34): run-time error JS1014: Invalid character: `
(1488,19-20): run-time error JS1010: Expected identifier: [
(1488,53-54): run-time error JS1007: Expected ']': ;
(1638,14-15): run-time error JS1195: Expected expression: )
(1638,17-18): run-time error JS1195: Expected expression: >
(1641,5-6): run-time error JS1195: Expected expression: )
(1671,39-40): run-time error JS1195: Expected expression: >
(1671,56-57): run-time error JS1004: Expected ';': )
(1777,22-23): run-time error JS1195: Expected expression: )
(1785,70-71): run-time error JS1014: Invalid character: `
(1785,75-76): run-time error JS1006: Expected ')': {
(1785,87-88): run-time error JS1003: Expected ':': }
(1785,88-89): run-time error JS1004: Expected ';': )
(1785,89-90): run-time error JS1014: Invalid character: `
(1785,91-92): run-time error JS1197: Too many errors. The file might not be a JavaScript file: :
(1629,1-54): run-time error JS1301: End of file encountered before function is properly closed: function BuscarPublicacion(idsolicitud, tipoBusqueda)
(1785,93-94): run-time error JS1014: Invalid character: `
(1785,96-97): run-time error JS1006: Expected ')': {
(1785,109-110): run-time error JS1195: Expected expression: )
(1785,110-111): run-time error JS1014: Invalid character: `
(1785,111-112): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ;
(1447,1-37): run-time error JS1301: End of file encountered before function is properly closed: function FormatearFechaGaceta(fecha)
(1786,19-20): run-time error JS1014: Invalid character: `
(1786,20-21): run-time error JS1014: Invalid character: #
(1786,22-23): run-time error JS1193: Expected ',' or ')': {
(1786,29-30): run-time error JS1002: Syntax error: }
(1786,30-31): run-time error JS1014: Invalid character: `
(1786,31-32): run-time error JS1197: Too many errors. The file might not be a JavaScript file: )
 */
// *** TRIM ***
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
}

// *** REPLACE ALL ***
// Replaces all instances of the given substring.
String.prototype.replaceAll = function(
	strTarget, // The substring you want to replace
	strSubString // The string you want to replace in.
	) {
    var strText = this;
    var intIndexOfMatch = strText.indexOf(strTarget);

    // Keep looping while an instance of the target string
    // still exists in the string.
    while (intIndexOfMatch != -1) {
        // Relace out the current instance.
        strText = strText.replace(strTarget, strSubString)

        // Get the index of any next matching substring.
        intIndexOfMatch = strText.indexOf(strTarget);
    }

    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return (strText);
}

// *** ENDS WITH ***
String.prototype.endsWith = function(suffix) {
    var startPos = this.length - suffix.length;
    if (startPos < 0) {
        return false;
    }
    return (this.lastIndexOf(suffix, startPos) == startPos);
};

// *** FORMAT ***
function _StringFormatInline() {
    var txt = this;
    for (var i = 0; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
        txt = txt.replace(exp, arguments[i]);
    }
    return txt;
}
function _StringFormatStatic() {
    for (var i = 1; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        arguments[0] = arguments[0].replace(exp, arguments[i]);
    }
    return arguments[0];
}
if (!String.prototype.format) {
    String.prototype.format = _StringFormatInline;
}
if (!String.format) {
    String.format = _StringFormatStatic;
}




var keyStr = "ABCDEFGHIJKLMNOP" +
             "QRSTUVWXYZabcdef" +
             "ghijklmnopqrstuv" +
             "wxyz0123456789+/" +
             "=";

function encode64(input) {
    input = escape(input);
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;

    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
           keyStr.charAt(enc1) +
           keyStr.charAt(enc2) +
           keyStr.charAt(enc3) +
           keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);

    return output;
}

function decode64(input) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;

    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    var base64test = /[^A-Za-z0-9\+\/\=]/g;
    if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" +
              "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
              "Expect errors in decoding.");
    }
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

    } while (i < input.length);

    return unescape(output);
}
;

/* Upload Files */
function onkeyPress(e) {
    var key = window.event ? e.keyCode : e.which;
    if (key == 13)
        StartClick();
    e.cancelBubble = true;
    e.returnValue = false;
    return false;
}

function Validate(invalidFile, invalidType) {
    var objUpload = eval("document.getElementById('ctl00_MainContentPlaceHolder_filename')");
    var sUpload = objUpload.value;
    if (sUpload != "") {
        var iExt = sUpload.indexOf("\\");
        var iDot = sUpload.indexOf(".");

        if ((iExt < 0) || (iDot < 0)) {
            alert(invalidFile);
            objUpload.focus();
            event.returnValue = false;
            return false;
        }
        if (iDot > 0) {
            var aUpload = sUpload.split(".");
            if (aUpload[aUpload.length - 1] != "jpg" && aUpload[aUpload.length - 1] != "JPG" && aUpload[aUpload.length - 1] != "bmp" && aUpload[aUpload.length - 1] != "png") {
                alert(invalidType);
                objUpload.focus();
                event.returnValue = false;
                return false;
            }
        }
    }
}
/* end Upload Files */

function getElementsByClassName(classname, node) {
    if (!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for (var i = 0, j = els.length; i < j; i++)
        if (re.test(els[i].className)) a.push(els[i]);
    return a;
}

//create function, it expects 2 values.
function insertAfter(newElement, targetElement) {
    //target is what you want it to go after. Look for this elements parent.
    var parent = targetElement.parentNode;
    //if the parents lastchild is the targetElement...
    if (parent.lastchild == targetElement) {
        //add the newElement after the target element.
        parent.appendChild(newElement);
    }
    else {
        // else the target has siblings, insert the new element between the target and it's next sibling.
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}

function insertImageAfterElementByClass(className, image) {
    elements = getElementsByClassName(className);
    for (i = 0; i < elements.length; i++) {
        tmpimg = document.createElement('img');
        tmpimg.src = image;
        insertAfter(tmpimg, elements[i]);
    }
}

function insertLinksIcons() {
    insertImageAfterElementByClass('NewLink', '/images/alerts/newicon.jpg');
    insertImageAfterElementByClass('ExternalLink', '/images/alerts/externallink.gif');
}

function FixFormAction() {
    var action = window.location;

    var formActionBase = document.getElementById('FormActionBase');
    if (formActionBase != null) {
        action = formActionBase.value;

        var actionStr = action;
        if (actionStr.endsWith(document.forms[0].action)) {
            return;
        }
    }

    document.forms[0].action = action;
}

/* 
* http://www.mediacollege.com/internet/javascript/form/limit-characters.html
*/
function InputLimitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}
// finds 'y' value of given object
function FindYPosition(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return [curtop];
    }
}

// scroll window in order to make the control visible
function ScrollTo(id) {
    var element = document.getElementById(id);
    var yPos = FindYPosition(element);
    yPos -= 10;
    window.scroll(0, yPos);
}

function EncodeHtml(decoded) {
    return decoded.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function DecodeHtml(encoded) {
    var decoded = jQuery('<textarea/>').html(encoded).val();
    return decoded;
}

function ShowConfirm(title, message, functionCall) {
    jQuery(document).ready(function () {
        var dialog = BootstrapDialog.show({
            id: 'ConfirmationDialog',
            title: title,
            message: message,
            onhide: function (dialogRef) {
                functionCall('#CancelarButton');
            },
            buttons: [{
                label: 'Aceptar',
                title: 'Aceptar',
                id: 'AceptarButton',
                cssClass: 'btn-primary',
                action: function (dialogItself) {
                    dialogItself.close();
                    functionCall('#AceptarButton');
                }
            },
            {
                label: 'Cancelar',
                title: 'Cancelar',
                id: 'CancelarButton',
                action: function (dialogItself) {
                    dialogItself.close();
                    functionCall('#CancelarButton');
                }
            }
            ]
        });
        dialog.getModalHeader().css('background-color', '#ffcb05');
    });
}

function ShowUserMessage(type, title, message) {
    jQuery(document).ready(function () {
        if (window.isMobileApp !== undefined && window.isMobileApp) {
            return;
        }

        var dialog = BootstrapDialog.show({
            title: title,
            message: message
        });

        if (type == 1) {
            dialog.getModalHeader().css('background-color', '#00a651');
        } else if (type == 2) {
            dialog.getModalHeader().css('background-color', '#ffcb05');
        } else if (type == 3) {
            dialog.getModalHeader().css('background-color', '#ed1c24');
        } else if (type == 4) {
            dialog.getModalHeader().css('background-color', '#0080ff');
        }
    });
}

function ShowConfirmationMessage(title, message) {
    ShowUserMessage(4, title, message);
}

function SuccessMessage() {
    var message = jQuery('.successMessage').html();
    ShowUserMessage(1, '&Eacute;xito', message);
}
function SuccessMessage(message) {
    ShowUserMessage(1, '&Eacute;xito', message);
}

function InformationMessage() {
    var message = jQuery('.informationMessage').html();
    ShowUserMessage(2, 'Atenci&oacute;n', message);
}
function InformationMessage(message) {
    ShowUserMessage(2, 'Atenci&oacute;n', message);
}

function ErrorMessage() {
    var message = jQuery('.errorMessage').html();
    ShowUserMessage(3, 'Error', message);
}
function ErrorMessage(message) {
    ShowUserMessage(3, 'Error', message);
}

function GetZero() {
    return 0;
}

function GetEmpty() {
    return "";
}

function ShowLoadingImage(className, insertAfterSelector) {
    var htmlImage = jQuery('<img>');
    htmlImage.addClass(className);
    htmlImage.attr("src", _AppRoot + "/images/loadingIcon-inline.gif");
    htmlImage.attr("width", "16");
    htmlImage.attr("height", "11");
    jQuery(insertAfterSelector).after(htmlImage);
}

function ShowSuccessMessageLabel(text, insertAfterSelector) {
    var span = jQuery('<span>');
    span.addClass('SuccessMessageSpan');
    span.html(text);
    jQuery(insertAfterSelector).after(span);

    span.delay(3000).queue(function () {
        jQuery(this).remove();
    });
}

//inspirado en http://stackoverflow.com/questions/6115325/change-css-rule-in-class-using-jquery
function RedefinirDTTT_container() {
    var ss = null;

    for (var i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf('dataTables.editor.min.css') > -1) {
            ss = document.styleSheets[i];
            break;
        }
    }

    if (ss == null)
        return;

    var rules = ss.cssRules || ss.rules;
    var theRule = null;
    var rule = null;
    for (var i = 0; i < rules.length; i++) {
        rule = rules[i];
        if (rule.selectorText == 'div.DTTT_container')  //(/(^|,) *\.DTTT_container *(,|$)/.test(rule.selectorText)) 
        {
            theRule = rule;
            break;
        }
    }

    if (theRule != null) {
        theRule.style.display = "none";
    }
}

function SetControlToReadOnly() {
    ReemplazarControlesPorLabel("input.setToReadOnly:text", "input");
    ReemplazarControlesPorLabel("input.setToReadOnly:radio", "radio");
    ReemplazarControlesPorLabel("input.setToReadOnly:checkbox", "input");
    ReemplazarControlesPorLabel("input.setToReadOnly:checkbox", "checkbox");
    ReemplazarControlesPorLabel("select.setToReadOnly", "select");
}

function ActivarReadOnlyMode() {
    // elimina botones  
    jQuery(":button").not(".BotonVisible,.ControlVisible").hide();   //xxxremove
    jQuery(":submit").not(".BotonVisible,.ControlVisible").hide(); //xxxremove

    // elimina todos los contenedores de botones de DataTableTools (crear, eliminar, editar)
    //jQuery(".DTTT_container").remove();
    RedefinirDTTT_container();

    // deshabilita controles de captura
    jQuery(":checkbox").not(".ControlVisible").attr("disabled", "disabled");
    jQuery(":checkbox").not(".ControlVisible").addClass("readOnlyMode");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv :checkbox", "input");

    jQuery(":radio").attr("disabled", "disabled");
    jQuery(":radio").addClass("readOnlyMode");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv :radio", "radio");

    jQuery("select").not(".ControlVisible").attr("disabled", "disabled");
    jQuery("select").not(".ControlVisible").addClass("readOnlyMode");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv select", "select");

    jQuery("textarea").not(".ControlVisible").attr("disabled", "disabled");
    jQuery("textarea").not(".ControlVisible").addClass("readOnlyMode");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv :text", "input");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv textarea", "input");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv input[type='number']", "input");

    jQuery(":text").not(".ControlVisible").attr("disabled", "disabled");
    jQuery(":text").not(".ControlVisible").addClass("readOnlyMode");
    jQuery(":text").not(".ControlVisible").addClass("readOnlyMode readOnlyModeNoBorder");

    // fix de los RadioButtonList
    jQuery('.RadioButtonList').find('br').remove();

    // otros ...
    jQuery('.IndicarSedeDiv').css('display', 'none');
}

function ReemplazarControlesPorLabel(selector, controlType) {
    //console.log(selector);
    jQuery(selector).not(".ControlVisible").each(function (i) {
        var selectedItemText = "";
        var control = jQuery(this);
        var cssClass = "textControl";

        if (control.hasClass("form-control")) {
            cssClass += " form-control";
        }

        var ariaHidden = "";

        if (control.attr("class") != undefined && control.attr("class").indexOf('sr-only') <= 0) {

            if (typeof controlType == "undefined")
                controlType = control[0].tagName.toLowerCase();

            // select
            if (controlType == "select") {
                selectedItemText = control.find("option:selected").text();
                // input , textarea
            } else if (controlType == "input" || controlType == "textarea") {
                selectedItemText = control.val();

                if (control.attr("type") == "checkbox") {

                    selectedItemText = "";

                    if (control.hasAttr('checked')) {
                        cssClass = "glyphicon glyphicon-check";
                    }
                    else {
                        cssClass = "glyphicon glyphicon-unchecked";
                    }
                    ariaHidden = "aria-hidden=\"true\"";

                    var parentControl = control.parent();
                    if (parentControl.prop("tagName") == 'SPAN') {
                        parentControl.removeClass("form-control");
                        parentControl.addClass("checkBoxListReadOnly"); //para corregir la manera en que se muestran los checkboxlist
                    }
                }
                // radio , checkbox
            } else if (controlType == "radio" || controlType == "checkbox") {
                if (control.hasAttr('checked')) {
                    // busca el <label> asociado, toma el texto y luego lo remueve
                    var label = jQuery('label[for=' + control.attr("id") + ']');

                    selectedItemText = label.text();
                    label.hide(); //xxxremove
                }
                else {
                    // busca el <label> asociado y lo remueve
                    jQuery('label[for=' + control.attr("id") + ']').hide(); //xxxremove
                }
            }

            // reemplaza el control por un <span>

            //xxxRemove replaceWith
            //control.replaceWith("<span id='" + control.attr("name") + "' class=\"" + cssClass + "\"" + ariaHidden + ">" + selectedItemText + "</span>");
            control.after("<span id='" + control.attr("name") + "' class=\"" + cssClass + "\"" + ariaHidden + ">" + selectedItemText + "</span>");
            control.hide();

        }
        else { }
    });
}

function DetachValidationEngine() {
    jQuery('.MainForm').validationEngine('detach');
}

function ActivateInPlaceEditing() {
    var oldValue;
    var newValue;

    jQuery('.editArea').editable(_AppRoot + '/App_HttpHandlers/InPlaceEditing/UpdateField.ashx', {
        type: 'textarea',
        cancel: 'Cancelar',
        submit: 'Guardar',
        indicator: '<img src="' + _AppRoot + '/images/loadingIcon-inline.gif">',
        tooltip: 'Clic para editar ...',
        onsubmit: function (settings, original) {
            //
        },
        data: function (value, settings) {
            /* convert <br> to newline */
            var retval = value.replace(/<br[\s\/]?>/gi, '\n');
            return retval;
        },
        submitdata: function (value, settings) {
            /* HTML5 Custom Data Attributes (data-*) http://html5doctor.com/html5-custom-data-attributes/ */
            var itemid = jQuery(this).attr('data-idp-itemid');
            var code = jQuery(this).attr('data-idp-code');

            oldValue = this.revert;

            return {
                itemid: itemid,
                code: code
            };
        },
        callback: function (value, settings) {
            var object = jQuery(this);
            var data = jQuery.parseJSON(value);

            if (data.result == "1") {
                newValue = data.value;
                // set new value
                object.html(newValue);
                // user message
                var controlId = '#' + object.attr('id');
                ShowSuccessMessageLabel("Listo!", controlId);

                SuccessMessage(data.errormessage);
            } else {
                // restore old value
                object.html(oldValue);

                // error message
                ErrorMessage(data.errormessage);
            }

            // reset vars
            oldValue = "";
            newValue = "";
        }
    });
}

function IsEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

jQuery.fn.hasAttr = function (name) {
    return this.attr(name) !== undefined;
};
// bitacora
function MostrarBitacora(key1, key2, objeto) {
    //objeto debe venir schema.[tabla], o bien [tabla] cuando se usa dbo

    var initBitacoraModal = function (key1, key2, objeto) {
        var key2Filtro = 1;
        var key2Value = 1;
        if (key2 != null) {
            key2Filtro = 'key2';
            key2Value = key2;
        }
        $('#ViewAuditoriaTable').customeditor({
            dataTablesKey: "MantenimientoViewAuditoria",
            readOnly: true,
            dataTablesColumns:
                [
                    { data: 'id' },
                    { data: 'fechahora' },
                    {
                        data: 'evento',
                        "render":
                            function (val, type, row) {
                                if (val == 3)
                                    return "Editar";
                                else if (val == 1)
                                    return "Insertar";
                                else if (val == 2)
                                    return "Eliminar";
                                else
                                    return val + "Consultar";
                            }
                    },
                    { data: 'idUser' },
                    { data: 'ip' },
                    {
                        data: 'campos',
                        "render":
                            function (val, type, row) {
                                //faster than the Regexp version http://jsperf.com/replace-all-vs-split-join
                                return val.split('|').join(' | '); //reemplazar todos para favorecer wrap text                            
                            }
                    }
                ],
            filters: [
                { key: 'key1', value: key1, operator: '=' },
                { key: key2Filtro, value: key2Value, operator: '=' },
                { key: 'objeto', value: objeto, operator: '=' }
            ]
        });

        // get plugin data
        var viewAuditoriaPluginData = $('#ViewAuditoriaTable').customeditor('getData');

        // update filters
        viewAuditoriaPluginData.filters = [
            { key: 'key1', value: key1, operator: '=' },
            { key: key2Filtro, value: key2Value, operator: '=' },
            { key: 'objeto', value: objeto, operator: '=' }
        ]

        if (viewAuditoriaPluginData.isReady) {
            // reload data
            var table = $('#ViewAuditoriaTable').DataTable();
            table.ajax.reload();
            // sort by columns 1, and redraw
            table
                .order([1, 'desc'])
                .draw();
        }
        else {
            // init plugin
            $('#ViewAuditoriaTable').customeditor('initEditor');
        }

        // show modal
        $('#bitacoraModal').modal('show');
    };

    if ($('#bitacoraModal').length === 0) {
        // cargar Html del modal
        jQuery.ajax({
            url: _AppRoot + "/bitacora/popup.html",
            cache: false,
            dataType: 'html',
            success: function (data) {
                // append del Html del modal
                $('body').append(data);
                // init Modal
                initBitacoraModal(key1, key2, objeto);
            }
        });
    }
    else { // ya el Html del modal está cargado
        // init Modal
        initBitacoraModal(key1, key2, objeto);
    }
}

/* Para transformar un número a su representación agrupada, ej: 15000 y retornar un 15,000.00
 * http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
 * http://jsfiddle.net/hAfMM/435/
*/
Number.prototype.format = function (n, x) {
    var re = '(\\d)(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
    return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$1,');
};

var PAGEMODE_NOTSET = 0;
var PAGEMODE_NEW = 1;
var PAGEMODE_EDITING_EXISTING = 2;
var PAGEMODE_READONLY = 3;

//campos requeridos

//Bandera para desplegar el mensaje sobre campos en rojo
var mostrarErrorDeValidacionDeCampos = true;

//Setup del plugin de validator
var $validatorGeneral = jQuery("#aspnetForm").validator({ disable: false });
UpdateValidatorStuff();



//invalid.bs.validator	This event is fired when a form field becomes invalid. Field errors are provided via event.detail.
//Al encontrar el primer error.
//Se muestra mensaje con el significado de los campos en rojo
$validatorGeneral.on("invalid.bs.validator", function (e) {
    var $relatedTarget = jQuery(e.relatedTarget);
    if ((!$relatedTarget.hasAttr("data-datepicker"))
        && (!$relatedTarget.hasClass("FechaJQuery"))
        && ($relatedTarget.filter("input[type=email]").length == 0)
        && (!mostrarErrorDeValidacionDeCampos)) {
        mostrarErrorDeValidacionDeCampos = true;
        ErrorMessage("Los campos marcados en rojo contienen errores o son requeridos");
    }
});

//validated.bs.validator	This event is fired after a form field has been validated.
//Que ya no hay mas errores.
$validatorGeneral.on("validated.bs.validator", function () {
    try {
        var $pendientesCorregir = PendientesCorregir();
        $validatorGeneral('validate');
        /*        if ((mostrarErrorDeValidacionDeCampos) && ($pendientesCorregir.length == 0)) {
                    mostrarErrorDeValidacionDeCampos = false;
                }*/
    } catch (ex) { }
});

//validate.bs.validator	This event fires immediately when a form field is validated.
$validatorGeneral.on("validate.bs.validator", function () {
    try {
        var $pendientesCorregir = PendientesCorregir();
        if ($pendientesCorregir.length > 0) {
        }
    } catch (ex) { }
});

//valid.bs.validator	This event is fired when a form field becomes valid. Previous field errors are provided via event.detail.
//sin implementar
//Al momento de submit si hay errores ir al primero.
jQuery("#aspnetForm").on("submit", function (e) {
    mostrarErrorDeValidacionDeCampos = false;
    var $pendientesCorregir = PendientesCorregir();
    if ($pendientesCorregir.length <= 0)
        return; // exit
    GoToTabContainer($pendientesCorregir[0]);
});


jQuery(".validar[href*='__doPostBack']").on("click", function (e) {
    mostrarErrorDeValidacionDeCampos = false;
    $validatorGeneral.validator('validate');
    var $pendientesCorregir = PendientesCorregir();
    if ($pendientesCorregir.length <= 0) {
        return; // exit
    }
    e.preventDefault();
    GoToTabContainer($pendientesCorregir[0]);
});

function PendientesCorregir(selector) {
    var $invalidStuff;
    if (selector === undefined) {
        $invalidStuff = jQuery("input:invalid,select:invalid,textarea:invalid");
    } else {
        $invalidStuff = jQuery(selector).find("input:invalid,select:invalid,textarea:invalid");
    }

    return $invalidStuff;
}

function UpdateValidatorStuff() {
    jQuery("*[pattern]").not("*[data-pattern-error]").attr("data-pattern-error", "Formato de campo incorrecto");
    jQuery("*[type='email']").not("*[data-type-error]").attr("data-type-error", "Por favor ingrese un email válido");
    jQuery("*[type='number']").not("*[data-step-error]").not("*[step*='.']").attr("data-step-error", "Por favor ingrese un valor entero");
    jQuery("*[type='number']").not("*[data-step-error]").each(function () {
        var $this = jQuery(this);
        $this.attr("data-step-error", "Por favor ingrese un valor numérico con presición " + $this.attr("step"));
    });
    //jQuery("*[type]").not("*[data-type-error]").attr("data-type-error", "formato no es valido");
    jQuery("*[required]").not("*[data-required-error]").attr("data-required-error", "Campo requerido");

    jQuery(".form-control:required").parents(".form-group").addClass("has-feedback");

    /*
    jQuery("*[pattern]").each(function () {
        var $this = jQuery(this);
        if ($this.data("pattern-error") === undefined) {
            $this.data("pattern-error", "formato incorrecto");
        }
    }
    );*/


    //Se agrega antes de cada input marcado como requerido el span con el *
    try {
        jQuery("textarea[required], select[required], input[required]").prev("label").before("<span class='text-danger lead'>*</span>");


        jQuery(".form-control").each(function () {
            var $this = jQuery(this);
            var $inputGroup = $this.parents(".input-group");
            var $label = jQuery("label[for='" + this.id + "']");
            var $formGroup = $this.parents(".form-group");


            if ($label.length == 0) {
                $label = $formGroup.find("label");
                $label.attr("for", this.id);
            }
            $label.addClass("control-label");

            if (($this.filter(":required").length != 0)) {
                if ($formGroup.find(".text-danger.lead").length == 0) {
                    $label.before("<span class='text-danger lead'>*</span>");
                }


                if ($this.parents(".input-group").length != 0) {
                    $this = $inputGroup;
                }

                if ($this.nextAll(".help-block").length == 0) {
                    $this.after("<span class='help-block with-errors'></span>");
                }

                if ($this.nextAll(".form-control-feedback").length == 0) {
                    $this.after('<span class="glyphicon form-control-feedback" aria-hidden="true"></span>');
                }
            }
        });



    } catch (ex) {
    }
}


function GoToTabContainer(element) {
    jQuery(element).each(function () {
        var $this = jQuery(this);
        var parentTab = $this.parents(".tab-pane");
        if (parentTab.length > 0) {
            jQuery("a[href='#" + parentTab.attr("id") + "']").tab("show");
        }
        this.focus();
    });
}


function GetZero() {
    return 0;
}

function GetEmpty() {
    return "";
}

// Helper function to get 'now' as an ISO date string
function IsoDateString(strDate) {
    var d = new Date();

    if (strDate != undefined && strDate != null) {
        var newDate = new Date(strDate);

        if (newDate instanceof Date) {
            d = newDate;
        }
    }
    var pad = function (n) {
        return n < 10 ? '0' + n : n
    }

    return pad(d.getUTCDate()) + '/'
        + pad(d.getUTCMonth() + 1) + '/'
        + pad(d.getUTCFullYear())
};

function IsoDateTimeString(strDate) {
    var d = new Date();

    if (strDate != undefined && strDate != null) {
        var newDate = new Date(strDate);

        if (newDate instanceof Date) {
            d = newDate;
        }
    }
    var pad = function (n) {
        return n < 10 ? '0' + n : n
    }

    var day = pad(d.getUTCDate());
    var month = pad(d.getUTCMonth() + 1);
    var year = pad(d.getUTCFullYear());
    var h = d.getHours();
    var ampm = h >= 12 ? ' PM' : ' AM';
    h = h % 12;
    h = h == 0 ? 12 : h
    h = pad(h);
    var m = pad(d.getMinutes());
    var s = pad(0);

    return day + '/'
        + month + '/'
        + year + ' ' + h + ":" + m + ampm;
};

function InitDatepicker() {
    var isInlineEditingMode = ((typeof (_EDITING) != "undefined") && _EDITING);
    var inlineDatePickerSelector = ".DTE_Inline input[data-datepicker], .DTE_Inline .FechaJQuery";
    var currentDatePickerOptions = {
        format: "dd/mm/yyyy",
        todayBtn: true,
        language: "es",
        autoclose: true,
        todayHighlight: true,
        showOnFocus: true
    }

    if (isInlineEditingMode) {
        var inlineDatePickerOptions = {};
        jQuery.extend(inlineDatePickerOptions, currentDatePickerOptions);
        inlineDatePickerOptions.showOnFocus = false;

        jQuery(inlineDatePickerSelector)
            .datepicker("destroy")
            .datepicker(inlineDatePickerOptions)
            .datepicker("show")
            .on("hide", function () {
                this.focus();
            });
    }
    jQuery("input[data-datepicker] , .FechaJQuery")
        .not(inlineDatePickerSelector)
        .datepicker("destroy")
        .datepicker(currentDatePickerOptions);
    $('input[data-datepicker] , .FechaJQuery').datepicker('update');

}

function InitDateTimePicker() {
    var initDate = new Date();
    initDate.setSeconds(0);

    jQuery("input[data-datetimepicker] , .FechaHoraJQuery").datetimepicker({
        format: "dd/mm/yyyy HH:ii P",
        bootcssVer: 3,
        language: "es",
        autoclose: true,
        showMeridian: true,
        initialDate: initDate
    });
}

function InitializePopover() {
    $('[data-toggle="popover"]').popover({ trigger: 'focus' });
}

var GetIndexIfObjWithAttr = function (array, attr, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][attr] == value) {
            return i;
        }
    }
    return -1;
}


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 ExportarHTML2PDF(htmlText, fileName) {
    var handler = _AppRoot + "/App_HttpHandlers/HtmlToPDF.ashx";

    var postData = { html: htmlText, name: fileName, mode: "generate" };

    $.ajax({
        type: "POST",
        url: handler,
        data: postData,
        beforeSend: function () {
            SuccessMessage("La descarga iniciará en unos segundos..");
        },
        success: function (data) {

            window.location = handler + "?name=" + fileName + "&tempName=" + data.tempName;
            BootstrapDialog.closeAll();
        },

        traditional: true,
        error: function (xhr, status, p3, p4) {
            BootstrapDialog.closeAll();
            var err = "Error " + " " + status + " " + p3 + " " + p4;
            if (xhr.responseText && xhr.responseText[0] == "{")
                err = JSON.parse(xhr.responseText).Message;
            ErrorMessage(err);
        }
    });
}


function CreateModal($parent, title, content, buttons, shownCallback, closeCallback, destroyOnClose) {
    if (destroyOnClose === undefined) {
        destroyOnClose = true;
    }

    var popupTemplate =
        '<div class="modal fade" role="dialog" >' +
        '  <div class="modal-dialog modal-md">' +
        '    <div class="modal-content">' +
        '      <div class="modal-header">' +
        '        <button type="button" class="close" data-dismiss="modal">&times;</button>' +
        '        <h4 class="modal-title"></h4>' +
        '      </div>' +
        '      <div class="modal-body" />' +
        '      <div class="modal-footer">' +
        '      </div>' +
        '    </div>' +
        '  </div>' +
        '</div>';

    var $modal = $(popupTemplate);
    $modal.find(".modal-title").text(title);
    $modal.find(".modal-body").append(content);

    for (var i = 0; i < buttons.length; i++) {
        var currentButton = buttons[i];
        var $newButton = jQuery("<button type='button' class='btn'>");
        $newButton.text(currentButton.text);
        $newButton.click($modal, currentButton.onclick);

        if (currentButton.class !== undefined) {
            $newButton.addClass(currentButton.class);
        } else {
            $newButton.addClass("btn-default");
        }



        $modal.find(".modal-footer").append($newButton);
    }

    $parent.append($modal);

    $modal.modal();
    $modal.on('hidden.bs.modal', function () {
        if (closeCallback !== undefined && closeCallback != null) {
            closeCallback($modal);
        }
        if (destroyOnClose) {
            $(this).data('bs.modal', null);
        }
    });
    $modal.on('shown.bs.modal', function () {
        if (shownCallback !== undefined && shownCallback != null) {
            shownCallback($modal);
        }
    });
    return $modal;
}

//Se tomo de ejemplo pero se edito para que cumpliera las necesidades.
//https://stackoverflow.com/questions/22222599/javascript-recursive-search-in-json-object

function FindNode(currentNode, key, value) {
    var i,
        currentChild,
        result;

    if (currentNode[key] == value) {
        return currentNode;
    } else {

        // Use a for loop instead of forEach to avoid nested functions
        // Otherwise "return" will not work properly
        if (currentNode.items != undefined) {
            for (i = 0; i < currentNode.items.length; i++) {

                currentChild = currentNode.items[i];

                // Search in the current child
                result = FindNode(currentChild, key, value);

                // Return the result if the node has been found
                if (result !== false) {
                    return result;
                }
            }
        }

        // The node has not been found and we have no more options
        return false;
    }
}




function EjecutarPostAjax(url, formData, successAction, errorAction) {
    return new Promise(function (resolve, reject) {

        var isFormData = formData instanceof (FormData);

        var ajaxOptions = {
            url: url,
            data: formData,
            type: 'POST',
            success: function (data, textStatus, jqXHR) {

                if (typeof successAction !== 'undefined') {
                    successAction(data, textStatus, jqXHR);
                }
                var result = { data: data, textStatus: textStatus, jqXHR: jqXHR };
                resolve(result);
            },
            error: function (jqXHR, textStatus, errorThrown) {

                if (typeof errorAction !== 'undefined') {
                    errorAction(jqXHR, textStatus, errorThrown);
                }
                var result = { jqXHR: jqXHR, textStatus: textStatus, errorThrown: errorThrown };
                reject(result);
            }
        };

        //Manejo especifico de FormData
        if (isFormData) {
            ajaxOptions.processData = false;
            ajaxOptions.contentType = false;
        }

        jQuery.ajax(ajaxOptions);
    });
}

/*
•	FISICA: debe asegurar y validar que tenga 9 dígitos.
•	JURIDICA debe asegurar y validar que tenga 12 dígitos. OJO LUEGO DIJERON QUE 10
•	EXTRANJERO: debe validar que al menos tenga 12 dígitos. 
•	DIMEX (Documento de Identidad Migratorio para Extranjeros) debe asegurar y validar que tenga 12 dígitos. 
*/

function CheckFormato(tipoIdentificacion, source, args) {
    var exp = /^\d{9}$/;
    var text = args.Value;
    text = text.trim();
    switch (tipoIdentificacion) {
        case 1: //Física 
            exp = /^\d{9}$/;
            break;
        case 2: //Jurídica 
            exp = /^\d{10}$/;
            break;
        case 3: //Extranjera 
            exp = /^.{12,}$/;
            break;
        case 4: //DIMEX
            exp = /^\d{12}$/;
            break;
    }
    args.IsValid = exp.test(text)

}

function CheckFormatoCedula(source, args) {
    var tipoIdentificacion = $("input[name$='IdCatalogoTipoIdentificacion']:checked").val() * 1;
    CheckFormato(tipoIdentificacion, source, args);
}

function CheckFormatoCedulaFactura(source, args) {
    var tipoIdentificacion = $("input[name$='IdCatalogoTipoIdentificacionFacturas']:checked").val() * 1;
    CheckFormato(tipoIdentificacion, source, args);
}

function GetPlaceHolderYHelpIdentificacion(tipo) {

    var result = { placeHolder: "", helpText: "" };
    switch (tipo) {
        case 1:
            result.placeHolder = "101230456";
            result.helpText = "Debe introducir la cédula sin guiones. Ejemplo: 101230456 (9 dígitos)";
            result.maxChars = 9;
            break;
        case 2:
            result.placeHolder = "3101123456";
            result.helpText = "Debe introducir la cédula jurídica sin guiones. Ejemplo: 3101123456 (10 dígitos)";
            result.maxChars = 10;
            break;
        case 4:
            result.placeHolder = "123456789012";
            result.helpText = "Debe introducir el número de documento DIMEX. Ejemplo: 123456789012 (12 dígitos)";
            result.maxChars = 12;
            break;
        case 3:
            result.placeHolder = "123456789012";
            result.helpText = "Debe introducir el número de identificación como extranjero. Ejemplo: 123456789012 (al menos 12 dígitos)";
            result.maxChars = -1;
            break;
    }
    return result;
}


function SetupAyudasIdentificacion(radioListSelector, helpSelector, inputSelector) {
    $(radioListSelector).on("change", function () {
        var $this = $(this);
        var isChecked = $this.is(":checked");
        if (isChecked) {
            var helpPlaceHolder = GetPlaceHolderYHelpIdentificacion($this.val() * 1)
            $(helpSelector).text(helpPlaceHolder.helpText);
            $(inputSelector).attr("placeholder", helpPlaceHolder.placeHolder);

            //Manejo de maxLenght
            if (helpPlaceHolder.maxChars > 0) {
                $(inputSelector).attr("maxLength", helpPlaceHolder.maxChars);
            } else {
                $(inputSelector).removeAttr("maxLength");
            }

        }
    });
    $(radioListSelector + ":checked").trigger("change");
}


//#region https://hassoporte.atlassian.net/browse/HAS-530

function BuscarPorIdentificacionYTipo(tipo, identificacion, campoNombre) {
    var identificacionInput = $('#' + identificacion);
    var campoNombreInput = $('#' + campoNombre);
    var tipoInput = $('input[name$=' + tipo + ']'); //los radios desde radiolist en VS tienen esta patrón
    var tipoVal;

    for (var i = 0; i < tipoInput.length; i++) {
        if (tipoInput[i].checked) {
            tipoVal = tipoInput[i].value;
        }
    }

    EjecutarPostAjax(
        "/App_HttpHandlers/MobileAppHandler.ashx?accion=BuscarPorIdentificacionYTipo",
        {
            'tipo': tipoVal,
            'identificacion': identificacionInput.val()
        }
    ).then((response) => {

        if (response.data.Result) {
            campoNombreInput.val(response.data.Data.Nombre);
            campoNombreInput.prop("disabled", false);
            campoNombreInput.prop("readonly", true);

        }
        else {
            InformationMessage(response.data.Message);
            campoNombreInput.prop("readonly", false);
            campoNombreInput.prop("disabled", false);
        }
    });
}

//#endregion


function HermesObjectToHtml(content, template) {
    //https://stackoverflow.com/questions/36656679/substitute-string-with-placeholder-values-coming-from-json-object
    var replaced = "";

    var parts = template.split(/(\$\w+?\$)/g).map(function (v) {
        replaced = v.replace(/\$/g, "");
        return content[replaced] || replaced;
    });

    return parts.join("");
}

/*
var content = { "timeOfTheDay": "evening", "name": "Jack", "city": "New York", "age": "25" };
var str = "Good $timeOfTheDay$, $name$";

console.log(HermesObjectToHtml(content, str));
*/

function HermesOpenPopup(title, content) {
    var $genericModal = $("#genericModal");
    var html =
        '<div class="modal fade" id="genericModal" role="dialog" aria-labelledby="genericModalLabel" aria-hidden="true">' +
        '    <div class="modal-dialog  modal-lg">' +
        '        <div class="modal-content">' +
        '            <div class="modal-header">' +
        '                 <p class="modal-title" id="genericModalLabel"><strong id="xxxModalTitle">xxxModalTitle</strong></p>' +
        '            </div>' +
        '            <div class="modal-body" id="xxxModalBody">' +
        '               xxxModalBody' +
        '            </div>' +
        '            <div class="modal-footer">' +
        '                <button type="button" class="btn btn-primary" data-dismiss="modal">Cerrar</button>' +
        '            </div>' +
        '        </div>' +
        '    </div>' +
        '</div>';

    if ($genericModal.length == 0) {
        // $('#genericModal').modal('hide');
        $("body").append(html);
    } else {
        $genericModal.replaceWith(html);
        $(".modal-backdrop").remove();
    }
    //Como se reemplaza o se crea se tiene que recalcular genericModal
    $genericModal = $("#genericModal");

    $genericModal.removeAttr('style') //Esto se hace para quitar el style que agrega el aistente cuando se abre el pop-up
    $("#xxxModalTitle").html(title);
    $("#xxxModalBody").html(content);

    $genericModal.modal('show');
    setTimeout(function () {
        $(window).resize();
    }, 500);
}

//#region https://hassoporte.atlassian.net/browse/HAS-644 buscador inteligente
const TIPOBUSQUEDA_SOLICITUDPORTAL = 1;
const TIPOBUSQUEDA_NUMDOCASIGNADO = 2;
const TIPOBUSQUEDA_AUTOR = 3;
const TIPOBUSQUEDA_FECHA = 4;
const TIPOBUSQUEDA_GENERICA = 5;



function DerivarTipoBusquedaIssueHAS644(criterioDelUsuario) {
    var tipoBusqueda = TIPOBUSQUEDA_GENERICA;

    if (IsEmail(criterioDelUsuario)) {
        tipoBusqueda = TIPOBUSQUEDA_AUTOR; //El texto contiene arroba: se entenderá que es una búsqueda por autor
    }
    else {
        //El texto es un número y sus primeros 4 dígitos tiene la forma de un año entre 2012
        //y el año en curso: se interpreta que se trata de búsqueda por número de documento

        if (EsBusquedaPorNumeroDeDocumento(criterioDelUsuario)) {
            tipoBusqueda = TIPOBUSQUEDA_NUMDOCASIGNADO;
        }
        else {
            //El texto comienza con IN o RP y luego de esto es un número que cumple con el patrón
            //anterior: se procede como en el punto anterior

            const primerosDosCaracteres = criterioDelUsuario.substring(0, 2).toLowerCase();
            if (primerosDosCaracteres == 'in' || primerosDosCaracteres == 'rp') {

                if (EsBusquedaPorNumeroDeDocumento(criterioDelUsuario.substring(2))) {
                    tipoBusqueda = TIPOBUSQUEDA_NUMDOCASIGNADO;
                }
            }
        }

        //si aun no ha sido reconocido otro tipo
        if (tipoBusqueda == TIPOBUSQUEDA_GENERICA) {
            //Si el texto es un número y no coincide con el patrón B se realizará una
            //búsqueda por # de solicitud del portal y responderá lo mismo que responde el asistente virtual

            //Si sigue siendo un numero de documento pero anterior a 2011
            const regexNumDoc = /^(\d{4})(\d{6})$/g;
            const matches = [...criterioDelUsuario.matchAll(regexNumDoc)];
            let yearX = 0;

            if (matches.length > 0
                && 2003 <= (yearX = matches[0][1] * 1)
                && 2011 >= yearX
            ) {
                criterioDelUsuario = '(IN' + criterioDelUsuario + ')';
                $("#SolicitudInput").val(criterioDelUsuario);
            }

            const num = Number(criterioDelUsuario);
            if (Number.isInteger(num) && num.toString() === criterioDelUsuario) {
                tipoBusqueda = TIPOBUSQUEDA_SOLICITUDPORTAL;
            }

            else {
                var fechaReconocida = ReconocerFechas(criterioDelUsuario);

                if (fechaReconocida != null) {
                    fechaReconocida = FormatearFechaGaceta(fechaReconocida);

                    jQuery("#GacetasAnterioresDatePicker").val(fechaReconocida); //asignar al campo de búsqueda

                    tipoBusqueda = TIPOBUSQUEDA_FECHA;
                }
            }
        }
    }

    //estadísticas buscador "normal/viejo"
    if (tipoBusqueda == TIPOBUSQUEDA_FECHA || tipoBusqueda == TIPOBUSQUEDA_GENERICA) {

        EjecutarPostAjax(
            "/App_HttpHandlers/MobileAppHandler.ashx?accion=" + ((tipoBusqueda == TIPOBUSQUEDA_FECHA) ? "BuscadorPorFecha" : "BuscadorGenerico"),
            {
                'criterio': criterioDelUsuario
            }
        );
    }

    return tipoBusqueda;
}

function FormatearFechaGaceta(fecha) {
    const dia = fecha.getDate().toString().padStart(2, '0');
    const mes = (fecha.getMonth() + 1).toString().padStart(2, '0'); // Los meses son 0-indexados, así que se suma 1
    const año = fecha.getFullYear();

    return `${dia}/${mes}/${año}`;
}

function EsBusquedaPorNumeroDeDocumento(criterioDelUsuario) {
    // Extraer los primeros cuatro caracteres
    const primerosCuatroDigitos = criterioDelUsuario.substring(0, 4);

    // Convertir los primeros cuatro caracteres a número
    const primerosCuatroDigitosNum = parseInt(primerosCuatroDigitos, 10);

    const fecha = new Date();

    // Obtener el año
    const year = fecha.getFullYear() + 1

    // Comparar con 2012
    if (primerosCuatroDigitosNum >= 2012 && primerosCuatroDigitosNum <= year) {
        return true;
    }

    return false;
}

function ReconocerFechas(str) {
    // Definir las expresiones regulares para los diferentes formatos
    const patrones = [
        /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/,  // d/M/yyyy o dd/MM/yyyy
        /^(\d{1,2})-(\d{1,2})-(\d{4})$/    // d-M-yyyy o dd-MM-yyyy
    ];

    let fecha = null;

    // Intentar coincidir con cada patrón
    for (const patron of patrones) {
        const coincidencia = str.match(patron);
        if (coincidencia) {
            const [_, dia, mes, anyo] = coincidencia;

            if (mes > 12 || dia > 31) {

                continue;
            }

            fecha = new Date(anyo, mes - 1, dia); // En JavaScript, los meses son 0-indexados

            if (fecha instanceof Date && !isNaN(fecha.getTime())) {
                break;
            }
        }
    }

    return fecha;
}

//endregion
var mostrarMensajeSelectorDiario = false;
function GetSolicitudAsistenteOnClick(event, selector, omitirEjecutarBuscadorGeneral) {

    CreateBodyOverlay();

    $("#selectorDiario").addClass("hidden");

    if (omitirEjecutarBuscadorGeneral != true) {
        event.preventDefault();
    }

    var padre;
    if ($(event.target).parents(".chat-bot").length > 0) {
        padre = ".chat-bot";
    } else {
        padre = ".searchContainer";
    }

    //#region https://hassoporte.atlassian.net/browse/HAS-644 buscador inteligente
    var tipoBusqueda;

    if (padre == ".searchContainer") {
        var valorInput = $(padre + " #SolicitudInput").val().trim();

        tipoBusqueda = DerivarTipoBusquedaIssueHAS644(valorInput);

        //alert(tipoBusqueda);

        if (tipoBusqueda < TIPOBUSQUEDA_FECHA) {
            //seleccionar para ver que se hizo bien, estas son las 3 opciones del asistente
            $(padre + " input[name=tipoBusqueda]:checked").val(tipoBusqueda);
        }
        else {
            var radio;

            if (tipoBusqueda == TIPOBUSQUEDA_FECHA) {
                //debugger;
                var fechaReconocida = ReconocerFechas(valorInput);

                if (fechaReconocida > new Date(2023, 10, 23)) {
                    diario = GACETA;
                }
                else {

                    $("#selectorDiario").removeClass("hidden");

                    diario = $('input[name="selectorDiarioRadio"]:checked').val();

                    if (diario == GACETA || diario == BOLETIN) {
                        //seguir
                    }
                    else {
                        if (mostrarMensajeSelectorDiario) {
                            ErrorMessage("Debe indicar el tipo de diario y usar el botón 'Consultar' nuevamente")
                        }
                        //HAS-751 solo mostrar mensaje si no es la primera vez
                        mostrarMensajeSelectorDiario = true;
                        return;
                    }

                    /*
                    if (confirm("Presione Ok para ir a la Gaceta o Cancelar para ir al Boletín Judicial"))
                        diario = GACETA;
                    else
                        diario = BOLETIN;
                    */
                }

                radio = $('input[name="SearchGacetaType"][value="historica"]');
            }
            else {
                radio = $('input[name="SearchGacetaType"][value="generica"]');

                var idText = "GacetaGenericaInput";
                //Se vuelve a obtener el valorInput por si en el proceso se modifico en algo como haber agregado IN
                valorInput = $(padre + " #SolicitudInput").val().trim();
                jQuery("input[id$=" + idText + "]").val(valorInput);
            }


            radio.prop('checked', true);

            if (omitirEjecutarBuscadorGeneral != true) {
                //ejecutar buscador normal y este determinará si es genérico o por fecha
                jQuery("#BuscarGacetasAnterioresButton").click();
            }

            RemoveBodyOverlay();
            return tipoBusqueda;
        }
    }
    else {
        tipoBusqueda = $(padre + " input[name=tipoBusqueda]:checked").val();
    }

    //#endregion

    if (typeof tipoBusqueda === 'undefined') {
        ErrorMessage("Debe seleccionar un tipo de búsqueda");
    }
    else {

        var solicitud = $(padre + " #SolicitudInput").val();

        //console.log(solicitud);

		if (window._forzarBusquedaGenerica){
			console.log("Forzar Generica");
			return true;
		}

        if (solicitud !== "") {
            BuscarPublicacion(solicitud, tipoBusqueda);
            //console.log(solicitud);
        } else {
            ErrorMessage("Se debe ingresar un crierio de búsqueda");
        }
    }

    return tipoBusqueda;
}

function BuscarPublicacion(idsolicitud, tipoBusqueda) {

    EjecutarPostAjax(
        "/App_HttpHandlers/MobileAppHandler.ashx?accion=BuscarPublicacion",
        {
            'idsolicitud': idsolicitud,
            'tipoBusqueda': tipoBusqueda,
            'agregarComentarios': false
        }
    ).catch(() => {
        RemoveBodyOverlay();
    }
    ).then((response) => {
        if (response !== undefined) {


            RemoveBodyOverlay();

            var ESTADORECHAZADO = 11;
            var mostrarMensajeRechazado = false;
            var objetoSolicitud = response.data;

            // var todos = objetoSolicitud.map(objeto => Object.values(objeto));;
            var todos = objetoSolicitud;

            var unico = false;
            var urlTemplate = '/templates/templateConsultaTramiteAsistente.html';

            if (objetoSolicitud != null) {
                unico = objetoSolicitud.length == 1;

                objetoSolicitud = objetoSolicitud[0];

                if (unico)
                    urlTemplate = '/templates/templateConsultaTramiteAsistenteUnico.html';
            }


            if (objetoSolicitud) {

                fetch(urlTemplate + '?' + (new Date()).getMilliseconds())
                    // Exito
                    .then((response) => response.text())
                    .then((text) => {

                        const templateURLGaceta = '<a href="/$diario$/?date=$dia$/$mes$/$anyo$&doc=$IdInterno$">$PublicadoEn$</a> ';
                        const templateURLAlcance = '<a href="/ver/pub/$anyo$/$mes$/$dia$/ALCA$NumDiario$_$dia$_$mes$_$anyo$.pdf?$IdInterno$">$PublicadoEn$</a> ';

                        var template = text; /*"IdSolicitud:$IdSolicitud$" */

                        if (unico) {

                            mostrarMensajeRechazado = (objetoSolicitud.IdEstadoSolicitud == ESTADORECHAZADO);

                            PrepararObjectoLinkDiario(objetoSolicitud);

                            //if ($("PublicadoEn").text() == "Sin publicar") {
                            if (objetoSolicitud.anyo == 1) {
                                $("#PublicadoEn").parent().html("Sin publicar");
                            }

                            var content = HermesObjectToHtml(objetoSolicitud, template);

                            HermesOpenPopup("Resultado", content);

                            if (objetoSolicitud.anyo == 1) { //objetoSolicitud.FechaPublicacionReal == "") {
                                $("#PublicadoEn").replaceWith("Sin fecha de publicación");
                            }
                        }
                        else {
                            HermesOpenPopup("Resultado", template); //parece repetida con el if pero se ocupa el html del popup en el DOM para que funcione el llamado a Datatable()

                            $.each(todos, function (index, objeto) {
                                var fila = $('<tr>');

                                fila.append($('<td>').text(objeto.IdSolicitud));
                                //  fila.append($('<td>').text(objeto.NombreAnexo));
                                fila.append($('<td>').text(objeto.IdInterno));
                                fila.append($('<td>').text(objeto.EstadoSolicitud));
                                if (objeto.NumDiario == 0) {
                                    fila.append($('<td>').text(objeto.PublicadoEn));
                                }
                                else {
                                    var selectTemplate = (objeto.IdTipoDiario < 3) ? templateURLGaceta : templateURLAlcance;

                                    PrepararObjectoLinkDiario(objeto);

                                    var x = HermesObjectToHtml(objeto, selectTemplate);
                                    fila.append($('<td>').html(x));
                                }

                                //fila.append($('<td>').text(objeto.Avance));
                                // fila.append($('<td>').text(objeto.TipoDocumento));
                                mostrarMensajeRechazado = mostrarMensajeRechazado || (objeto.IdEstadoSolicitud == ESTADORECHAZADO);

                                $('#resultadosBusquedaPublicacionBody').append(fila);
                            });

                            include("/js_srv/incluir_dataTablesCustomList.js", {
                                dom: true, callback: function () {

                                    $('#resultadosBusquedaPublicacion').DataTable(
                                        {
                                            "paging": true,
                                            "pageLength": 5,
                                            "order": [[0, 'desc']],
                                            "oLanguage": { "sUrl": "/js_srv/datatables/es.txt" }
                                        });
                                }
                            });
                        }

                        //#region https://hassoporte.atlassian.net/browse/HAS-644 buscador inteligente
                        //se hace acá porque ya se tiene el html en el dom y acceso por tanto a jQuery
                        if (unico) {

                            if (objetoSolicitud.IdTipoDiario == 3) //se debe corregir al ser alcance
                            {
                                var fixedUrl = HermesObjectToHtml(objetoSolicitud, templateURLAlcance);

                                $("#PublicadoEn").html(
                                    fixedUrl
                                );
                            }

                            $.each(objetoSolicitud.OtrasPublicaciones, function (index, objeto) {

                                if (objeto.FechaPublicacionReal != objetoSolicitud.FechaPublicacionReal) {
                                    PrepararObjectoLinkDiario(objeto);

                                    objeto.IdInterno = objetoSolicitud.IdInterno; //copiar este dato

                                    var selectTemplate = (objeto.IdTipoDiario < 3) ? templateURLGaceta : templateURLAlcance;

                                    var x = HermesObjectToHtml(objeto, '<br>' + selectTemplate);

                                    $('#tdConListsDiarios').append(x);
                                }
                            });
                        }
                        //#endregion

                        $('#genericModal').css('z-index', '1000000');

                        $(".MensajeEstadoRechazados").hide();
                        if (mostrarMensajeRechazado) {
                            $(".MensajeEstadoRechazados").show();
                        }
                    })
                    .catch(err => console.log('Solicitud fallida', err)); // Capturar errores


            }
            else {
                let idText = "GacetaGenericaInput";
                //si es solo numeros agreguele el IN para buscar por (IN[idinterno])
                let fixedIdSolicitud = (/^\d+$/).test(idsolicitud) ? `(IN${idsolicitud})` : `(${idsolicitud})`;
                $(`#${idText}`).val(fixedIdSolicitud);
                BuscarGenerica(idText);
                //ErrorMessage("No se encontraron resultados con el criterio de búsqueda utilizado");
            }
        }
    });
}

function PrepararObjectoLinkDiario(objetoSolicitud) {
    var fecha = objetoSolicitud.FechaPublicacionReal;
    fecha = fecha.replace("/", "").replace("/", "");
    fecha = eval("new " + fecha);

    objetoSolicitud.diario = (objetoSolicitud.IdTipoDiario == 1) ? "gaceta" : "boletin";

    objetoSolicitud.dia = fecha.getDate();
    if (objetoSolicitud.dia < 10) { objetoSolicitud.dia = "0" + objetoSolicitud.dia; }

    objetoSolicitud.mes = fecha.getMonth() + 1;
    if (objetoSolicitud.mes < 10) { objetoSolicitud.mes = "0" + objetoSolicitud.mes; }

    objetoSolicitud.anyo = fecha.getFullYear();
}


function BuscarRecursivoEnListaDeObjetos(lista, campo, valor, campoLista) {

    for (var i = 0; i < lista.length; i++) {
        if (lista[i][campo] === valor) {
            return lista[i];
        } else {
            if (lista[i][campoLista].length > 0) {
                var result = BuscarRecursivoEnListaDeObjetos(lista[i][campoLista], campo, valor, campoLista);

                if (result)
                    return result;
            }
        }
    }


    return null; // Retorna null si no se encuentra ningún objeto con el valor buscado

}

function VerBusquedaSolicitud(soloRetornarHtml) {

    var itemBuscadorSolicitudes = 97;

    var item = BuscarRecursivoEnListaDeObjetos(_optionChatList, "id", itemBuscadorSolicitudes, "items");

    if (soloRetornarHtml)
        return item.respuesta;
    else
        HermesOpenPopup("Buscar publicacion", item.respuesta);
}

// Documentacion para aistente virtual
// Función asíncrona que maneja el evento de clic en un botón
async function GetSolicitudSumaAsistenteEjemploOnClick(event, selector1, selector2) {
    event.preventDefault(); // Previene el comportamiento predeterminado del evento (clic en un enlace o botón)
    var numero1 = document.getElementById(selector1).value; // Obtiene el valor del primer elemento del DOM
    var numero2 = document.getElementById(selector2).value; // Obtiene el valor del segundo elemento del DOM

    try {
        if (numero1 !== "" && numero2 !== "") { // Verifica si ambos números no están vacíos
            var suma = await sumaAsistenteEjemplo(numero1, numero2); // Llama a la función para sumar los números

            var $btn = $(event.target); // Obtiene el elemento que desencadenó el evento
            console.log("Numeros", suma); // Muestra los números sumados en la consola

            // Crea un nuevo div con el resultado de la suma y lo coloca antes del botón que desencadenó el evento
            var $resultado = $("<div class='form-control'>Resultado: " + suma + "</div> </br>");
            $btn.before($resultado);
        } else {
            ErrorMessage("Se debe ingresar dos numeros"); // Muestra un mensaje de error si los números están vacíos
        }
    } catch (error) {
        ErrorMessage("Error en la suma"); // Muestra un mensaje de error si hay un problema en la suma
    }
}

// Función para sumar los números haciendo una solicitud AJAX
function sumaAsistenteEjemplo(numero1, numero2) {
    return new Promise((resolve, reject) => {
        // Realiza una solicitud AJAX al servidor para sumar los números
        EjecutarPostAjax(
            "/App_HttpHandlers/MobileAppHandler.ashx?accion=sumaAsistenteEjemplo",
            {
                'numero1': numero1,
                'numero2': numero2
            }
        ).then((response) => {
            var data = response.data; // Obtiene los datos de la respuesta
            console.log("data", data); // Muestra los datos en la consola

            if (data) {
                resolve(data); // Resuelve la promesa con el resultado numérico
            } else {
                reject("Error: Error de servidor"); // Rechaza la promesa si hay un error en los datos recibidos
            }
        }).catch((error) => {
            reject("Error en la solicitud Ajax: " + error); // Rechaza la promesa en caso de error en la solicitud AJAX
        });
    });
}


function ValidateKeypressUsingPattern(regex) {
    try {

        var $this = $(event.target);
        var keyChar = String.fromCharCode(event.which || event.keyCode);
        if (regex.test(keyChar) == false) {
            setTimeout(function () {
                var beforeValue = $this.val();
                $this.val(beforeValue.replace(keyChar, ''));
            }, 10);
        }
    } catch (ex) {
        console.error(ex);
    }
}

function removeAccents(str) {
    return str
        .replace(/[àáâãäå]/g, "a")
        .replace(/[ÀÁÂÃÄÅ]/g, "A")
        .replace(/[èéêë]/g, "e")
        .replace(/[ÈÉÊË]/g, "E")
        .replace(/[ìíîï]/g, "i")
        .replace(/[ÌÍÎÏ]/g, "I")
        .replace(/[òóôõö]/g, "o")
        .replace(/[ÒÓÔÕÖ]/g, "O")
        .replace(/[ùúûü]/g, "u")
        .replace(/[ÙÚÛÜ]/g, "U")
        .replace(/[ýÿ]/g, "y")
        .replace(/[ÝŸ]/g, "Y")
        .replace(/[ñ]/g, "n")
        .replace(/[Ñ]/g, "N")
        .replace(/[ç]/g, "c")
        .replace(/[Ç]/g, "C")
        .replace(/[œ]/g, "oe")
        .replace(/[Œ]/g, "OE")
        .replace(/[æ]/g, "ae")
        .replace(/[Æ]/g, "AE");
}


//Dejar siempre al final
$(document).ready(function () {
    if (typeof $.fn.datepicker != "undefined") {
        InitDatepicker();
    }
    if (typeof $.fn.datetimepicker != "undefined") {
        InitDateTimePicker();
    }

    if (typeof pageMode != 'undefined') {
        if (pageMode === PAGEMODE_READONLY) {
            ActivarReadOnlyMode();
        } else {
            SetControlToReadOnly();//si la página no es readonly, pueden haber controles que si lo sean
        }
    }

    setTimeout(function () {
        if (ValidateKeypressUsingPattern !== undefined) {
            $("input[data-allowonlynumebers]")
                .on("keypress",
                    function () {
                        ValidateKeypressUsingPattern(/[0-9]/)
                    });
        }
    }, 1000);

    $(document).on("change", 'input[type=radio][name=tipoBusqueda]',
        function (sender) {

            var val = $(sender.target).val();
            var msg = null;
            if (val == 1)
                msg = "Digite el número de solicitud asignado en el Portal Web.";
            else if (val == 2)
                msg = "Digite el número de documento indicado en la factura o el número de documento asociado a la solicitud Web"
            else
                msg = "Digite el correo electrónico que utilizó para crear la solicitud Web.";

            if (msg != null) {
                $('label[for=SolicitudInput').text(msg);
            }
        })

    //#region https://hassoporte.atlassian.net/browse/HAS-644 buscador inteligente

    $('form[action^="/buscador/"]').submit(function (event) {
		if(window._forzarBusquedaGenerica){
			return true;
		}
        var inputBuscador = jQuery("#ctl00_MainContentPlaceHolder_BuscadorWebUserControl1_CriterioTextBoxArriba");

        var inputBuscadorAsistente = $(".searchContainer #SolicitudInput");

        //pasar los datos a este campo para que funcione la lógica interna de método GetSolicitudAsistenteOnClick
        inputBuscadorAsistente.val(inputBuscador.val());

        //la llamada anterior ejecutaría un event.preventDefault(); cuando sea necesario (se usó el nuevo buscador)

        //el true es para que no ejecute el buscasdor genérico desde el método
        //sino desde el submit normal para que tenga acceso a otroas variables como ordenamiento, paginación , etc
        var tipo = GetSolicitudAsistenteOnClick(event, null, true);
        if (tipo <= TIPOBUSQUEDA_FECHA) {
            event.preventDefault();
        }

        if (tipo == TIPOBUSQUEDA_FECHA) {
            jQuery("#BuscarGacetasAnterioresButton").click();
        }

    });

    $(".imageWithLink").on("click", function (sender) {
        debugger;
        window.location = sender.prop("href");
    });

    //#endregion 
});;
// prevent a Form submir with ENTER
document.onkeypress = function (objEvent) {
    if (!objEvent)
        var objEvent = window.event; // IE
    if (objEvent === undefined)
        objEvent = window.event; // fix IE

    // check if the target is a textarea element
    var elem = (objEvent.target) ? objEvent.target : objEvent.srcElement;
    if (elem.type == "textarea") {
        // a textarea has the focus, allow Enter
        return true;
    }

    if (elem.tagName == "A") {
        // a textarea has the focus, allow Enter
        return true;
    }

    if (objEvent.keyCode == 13) // enter key
    {
        var target = objEvent.target;
        if (!target)
            target = objEvent.srcElement; // fix IE
        if (objEvent === undefined)
            target = objEvent.srcElement; // fix IE

        var control = jQuery("#" + target.id);
        var controlType = control.attr("type");
        if (controlType == "password") {
            jQuery(".LoginSubmitButton").click();
        }


        return false; // this will prevent bubbling ( sending it to children ) the event!
    }
}

function FixRadioStyle() {
    jQuery(":radio").css("border", "none");
    jQuery(":radio").each(function () {
        $(this).after("&nbsp;");
    });

    jQuery(":checkbox").css("border", "none");
    jQuery(":checkbox").each(function () {
        $(this).after("&nbsp;");
    });
}
;
var urlp = "";
var originalFontSize = jQuery('.MsoNormal').css('font-size');
var max = 4;
var min = -3;
var fixMegadropdowMenu = true;
var HASPageOffset = 50;
var GoogleApiKey = 'xxx';
var GTag = 'G-PMR4TLVH23';
var CurrentLayoutId = null;
var _isMuseoDiariosOficiales = location.hostname.match(/^(museo|historico)/i);

RevisarDependencias();

function IrABoletinEnGaceta() {
    const urlParams = new URLSearchParams(window.location.search);
    const myParam = urlParams.get('IrABoletinEnGaceta');

    if (myParam == "true") {
        $("a:contains('NOTIFICACIONES')").click();
    }
}

function llamadosHermes(sitio) {
    if (urlp != "")
        urlp = "/redirect.php?URL=http://" + urlp;

    //Cambio de color basico
    //ColorChangeSetup();
    jQuery(".WordSection1 img,.nav img, #PageContent img").addClass("img-responsive");

    ReplaceLinksWithContent(function () {
        convertHermesContainer();
        jQuery("div[id*='_MenuPiePagina_'] a, div[id*='_MenuContextual_'] a").attr("tabindex", "0").attr("aria-expanded", "true");
        var $HASContextImageContainer = jQuery("#ctl00_HASContextImage_HASContextImageContainer");
        if ($HASContextImageContainer.length > 0) {
            $HASContextImageContainer.attr("src", $HASContextImageContainer.attr("src") + "?mode=crop&h=" +
                (window.innerWidth >= 768 ? 200 : 100)
                + "&w=" + window.innerWidth);
            var nombreSubsitio = $(".HASBreadCrumbs a:last").text();
            if (nombreSubsitio.length > 0 && nombreSubsitio != 'Inicio')
                $HASContextImageContainer.before("<span class='ImagenContextualCaption'>" + nombreSubsitio + "</span>");
            else
                $HASContextImageContainer.before("<span class='ImagenContextualCaption'>" + $("h1:first").text() + "</span>");
        }
        if (jQuery("#ficha, .FichaArchivoContainer").length == 0) {
            jQuery(".addOns").after("<div class='clear'></div>");
        }
        fixFooterMenu();
        fixLeftSideBarMenu();
        fixLayout();
        fixForms();
        InitDatepicker();
        TabsHistory();
        SetupFontResize();
        fixBuscadorNumDoc("BuscarMasterButton", "expresion");
        fixBuscadorNumDoc("BuscarGacetasAnterioresButton", "GacetaGenericaInput");
        jQuery("#expresion,#GacetaGenericaInput,#GacetasAnterioresDatePicker").keypress(function (e) {
            if (e.which == 13) {
                jQuery("#BuscarGacetasAnterioresButton").click();
            }
        });
        //////FIXES megadropdown-menu ///////////////////////
        if ((typeof (fixMegadropdowMenu) != "undefined") && fixMegadropdowMenu) {
            var navbarWidth = jQuery("#ctl00_MenuPrincipal_HASMenuContainer .navbar-nav").get(0).clientWidth;
            var navbarCenter = navbarWidth / 2;
            var colsize = navbarWidth / 4;
            jQuery(".mega-dropdown-menu").not("#MenuMobileContainer .mega-dropdown-menu").each(function () {
                var $this = jQuery(this);
                var submenusCount = $this.find(" > li > ul").length;
                if (submenusCount > 1) {
                    var colsClass = "";
                    switch (submenusCount) {
                        case 2: colsClass = "col-sm-6"; break;
                        case 3: colsClass = "col-sm-4"; break;
                        case 4: colsClass = "col-sm-3"; break;
                        case 5:
                        case 6: colsClass = "col-sm-2"; break;
                    }

                    $this.width(colsize * submenusCount);
                    $this.find(".calcularCols").addClass(colsClass).removeClass("calcularCols");
                }
                var $megadropdown = $this.parents(".mega-dropdown").eq(0);
                if ($megadropdown.offset().left > navbarCenter) {
                    $this.css({ right: 0, left: "auto" });
                }
            });
        }
        //esto es para los rss 2/nov/2018 //
        var NoticiasXmlFileDefault = "/noticias/rss.xml";
        var NoticiasXslFileDefault = "/xsl/noticias.xsl";
        var NoticiasXmlFile, NoticiasXslFile = "";

        $(".rssFeed").each(function (index) {
            var attrXML = $(this).attr("data-xml");
            var attrXSL = $(this).attr("data-xsl");
            NoticiasXmlFile = NoticiasXmlFileDefault;
            NoticiasXslFile = NoticiasXslFileDefault
            if (typeof attrXML !== typeof undefined && attrXML !== false) {
                NoticiasXmlFile = attrXML;
            }
            if (typeof attrXSL !== typeof undefined && attrXSL !== false) {
                NoticiasXslFile = attrXSL;
            }
            $(this).attr("id", $(this).attr("id") + index);
            var ID = $("#" + $(this).attr("id"));
            RenderRSSWidget(ID, NoticiasXmlFile, NoticiasXslFile);
        })

        setTimeout(function () {
            if (typeof AfterConvertHermesContainerCallbacks != 'undefined') {
                for (i = 0; i < AfterConvertHermesContainerCallbacks.length; i++) {
                    AfterConvertHermesContainerCallbacks[i]();
                }
                jQuery(window).resize();
            }
            window.SetupAccessFix !== undefined && SetupAccessFix();
        }, 500);


        /*Museo menu fixes*/

        if (window._isMuseoDiariosOficiales) {
            fixesMuseoDiarios();
        }


    })

    jQuery(".Section1 img[alt^='UserControl:'], .WordSection1 img[alt^='UserControl:']").each(function () {
        var $this = jQuery(this);
        var userControlName = this.alt.replace("UserControl:", "");
        var $userControl = jQuery("#" + userControlName);
        $this.replaceWith($userControl);
    });
    //$(".addOns:first").append("<div><span class='pull-right hidden'>compartir contenido</span><div class='addthis_inline_share_toolbox'></div>");
    /////esto no se debe borrar, sirve para abrir los acordeones desde el mapa
    jQuery(document).ready(function () {
        $(window).on('hashchange', function (e) {
            var selecctedHash = window.location.hash;
            var currentHref = window.location.pathname;
            var url = currentHref + selecctedHash;
            jQuery("a[href^='" + selecctedHash + "']").click();
        });
    });
    $(document).ready(ConvertDivToLink());

    $(".MenuByRolesDiv a[href='#']").parents("li").addClass("MemuGrupo");

}


function ConvertDivToLinkOriginal() {
    var newRule = ".divToLink p,.divToLink a, .divToLink a span {color: white !important;}.divToLink{transition: all 300ms ease-in-out; background-color:#f7a600; padding:10px; } .divToLink:hover { !important; background:#ec8627;transform: scale(1.01);-webkit-box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.5);-moz-box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.5);box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.5); }";
    $("style").append(newRule);
    $(".DivToLink").find(".row").each(function (index) {
        var divH = 0;
        $(this).find("div").each(function (index) {
            $obj = $(this);
            if ($obj.find("a").length > 0)
                if ($obj.find("a").length == 1)
                    $obj = $obj.find("a");
                else
                    $obj = $obj.find("a").closest("div");
            else
                $obj = $obj.find("p").parent();
            $obj.wrapInner("<div class='divToLink'/>");
            var altura = $(this).height();
            if (altura > divH) {
                divH = $(this).height();
            }
        });
        $(this).css("padding", "20px");
        $(this).find("div").height(divH);
        $(this).find("div").css("color", "white");
        $(this).find("div").addClass("tramitesText");
        $(this).find("div>p").addClass("tramitesText");
        $(this).css("marginBottom", "10px");
        $(this).css("marginTop", "10px");

    });
}


function ConvertDivToLink() {
    var newRule = ".divToLink p,.divToLink a, .divToLink a span {color: white !important;}.divToLink{transition: all 300ms ease-in-out; background-color:#f7a600; padding:10px; } .divToLink:hover { !important; background:#ec8627;transform: scale(1.01);-webkit-box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.5);-moz-box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.5);box-shadow: 5px 5px 5px 0px rgba(0,0,0,0.5); }";
    $("style").append(newRule);
    $(".DivToLink").find(".row").each(function (index) {
        var divH = 0;
        $(this).find("div").each(function (index) {
            $obj = $(this);
            $anc = $obj.find("a");
            $anc.each(function (index) {
                var $span = $('<span style="color: white !important;">');
                $(this).after($span.html($(this).html())).remove();
            });
            $obj.wrapInner("<div class='divToLink'/>");
            if ($anc.attr("href") != undefined) {
                $obj.wrapInner("<a href='" + $anc.attr("href") + "'/>");
            }
            var $link = $(".SpellE");
            var $span = $('<span">');
            $link.after($span.html($link.html())).remove();
            var altura = $(this).height();
            if (altura > divH) {
                divH = $(this).height();
            }
        });
        $(this).css("padding", "20px");
        $(this).find("div").height(divH);
    });
}



//////////////
function fixForms() {
    jQuery(".WordSection1 input:not([type=radio],[type=checkbox]),.WordSection1 select,.WordSection1 textarea").each(function () {
        var $this = jQuery(this);
        var $newFormGroup = jQuery("<div class='form-group'>");
        var $pContainer = $this.parents("p").eq(0);
        var controlClass = "";
        switch ($this.attr("type")) {
            case "button":
            case "submit": controlClass = "btn"; break;
            default: controlClass = "form-control";
        }

        $this.addClass(controlClass);
        if (typeof ($pContainer) != 'undefined') {
            $pContainer.before($newFormGroup);
            $newFormGroup.append($pContainer.contents());
            $pContainer.remove();
        }
    });
}

function fixLayout() {
    var exceptions = ".TableNoConvertToDiv,table[id^='HASCustomList_'] ,.indice_contenido,.dataTable ,.SimpleDataTable,.HERMESCUSTOMLIST,.HERMESIGNORETABLETOGRID,.HERMESACCORDION,.HERMESTABS,.HERMESVTABS,.HERMESFORMS,.ui-jqgrid-btable,.ui-jqgrid-htable,.ui-pg-table,.ui-pg-table,.datetimepicker,.customeditor";
    jQuery("table").not(exceptions).each(function () {
        var $currentTable = jQuery(this);
        var $newConvertedTable = jQuery("<div class='TableConverted'>");

        var SpanColsByRowSpanArray = new Array;
        if ($currentTable.parents(exceptions).length == 0) {
            $currentTable.find(" > tbody > tr").each(function () {
                var $currentRow = jQuery(this);
                var $rowCols = $currentRow.find(">td");
                var cols = $rowCols.length;
                var $newRow = jQuery("<div class='row'>");
                var colClass = "";

                var colSpan = 0;
                $currentRow.find(">td[colspan]").each(function () {
                    colSpan += (jQuery(this).attr("colspan") * 1) - 1;
                });
                cols += colSpan;

                switch (cols) {
                    case 1: colClass = "col-xs-12 overflowHidden"; break;
                    case 2: colClass = "col-sm-6 text-left-sm text-left-xs overflowHidden"; break;
                    case 3: colClass = "col-sm-4 text-left-sm text-left-xs overflowHidden"; break;
                    case 4: colClass = "col-sm-3 text-left-xs overflowHidden"; break;
                    case 6: colClass = "col-sm-2 text-left-xs overflowHidden"; break;
                    case 12: colClass = "col-sm-1 text-left-xs overflowHidden"; break;
                }

                $rowCols.each(function () {
                    var $currentCol = jQuery(this);
                    var thisColClass = colClass;

                    colSpan = $currentCol.attr('colspan');
                    if (colSpan) {
                        var x = Math.round(colSpan / cols * 12);
                        //alert(x);
                        thisColClass = "col-sm-" + x + " text-left-sm text-left-xs overflowHidden";
                    }



                    var thisRowSpan = $currentCol.attr("rowspan") * 1;
                    var $newCol = jQuery("<div>");
                    $newCol.addClass(thisColClass);

                    $newCol.append($currentCol.contents());
                    $newRow.append($newCol);
                    if (thisRowSpan) {
                        $newCol.attr("data-rowspan", thisRowSpan);
                        SpanColsByRowSpanArray.push(thisRowSpan);
                    }

                });
                //Ignorar celdas vacios
                if (jQuery.trim($newRow.text()) != "" ||
                    ($newRow.find("video,audio,iframe,img,input,textarea,button,select,table.ExcelToTable").length > 0)) {
                    $newConvertedTable.append($newRow);
                }
            });


            $currentTable.before($newConvertedTable);
            $currentTable.remove();

            jQuery("div[data-rowspan]").each(function () {
                var $this = jQuery(this);
                alert($this.attr("data-rowspan"));
            });
        }
    });


    jQuery("table.HERMESIGNORETABLETOGRID").each(function () {
        var $thisTable = jQuery(this);
        $thisTable.after($thisTable.find("tr:nth-child(2) > td:first > *"));
        $thisTable.remove();
    });

}



function fixFooterMenu() {
    var $footerMenu = jQuery("footer .nav ");
    $footerMenu.find(".dropdown").removeClass("dropdown mega-dropdown");
    $footerMenu.find(".dropdown-toggle").removeClass("dropdown-toggle");
    $footerMenu.find(".dropdown-menu").removeClass("dropdown-menu mega-dropdown-menu");
    $footerMenu.find(".caret").remove();
}


function fixLeftSideBarMenu() {
    var $LeftSideBarMenu = jQuery(".LeftSideBarContainer .nav ");
    $LeftSideBarMenu.find(".dropdown").removeClass("dropdown mega-dropdown");
    $LeftSideBarMenu.find(".dropdown-toggle").removeClass("dropdown-toggle");
    $LeftSideBarMenu.find(".dropdown-menu").removeClass("dropdown-menu mega-dropdown-menu");
    $LeftSideBarMenu.find(".caret").remove();
}

function CambiarAction(boton) {
    if (boton == document.getElementById("botonBuscarMobile")) {
        $("#expresion").val($("#expresionMobile").val());

    }

    var form = $("#aspnetForm");
    form.prop("action", "/buscador/default.aspx");

    var vs = document.getElementById("__VIEWSTATE");
    if (typeof (vs) != "undefined") { vs.value = ""; }
}
function InitDatepicker() {
    if (typeof $.fn.datepicker == "undefined") { return; }

    jQuery("input[data-datepicker] , .FechaJQuery").datepicker({
        format: "dd/mm/yyyy",
        todayBtn: true,
        language: "es",
        autoclose: true,
        todayHighlight: true
    });
}

function TabsHistory() {
    if (location.hash !== '') {
        var targetTab = $('a[href="' + location.hash + '"]');
        targetTab.parents("[role='tabpanel']").each(function () {
            jQuery('a[href="#' + this.id + '"]').tab('show');
        });
        targetTab.tab('show');
    }

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var targetHash = $(e.target).attr('href').substr(1);
        var $element = jQuery("#" + targetHash);
        $element.attr("id", null);
        location.hash = targetHash;
        $element.attr("id", targetHash);
    })
}



////////////////////////////////
function RenderRSSWidget2(selector, currentXML, isHome) {
    var currentXSL = isHome ? "/xsl/rssHome.xsl" : "/xsl/noticias.xsl";

    if (jQuery(selector).length == 0)
        return;

    jQuery(selector).transform({
        xml: currentXML, xsl: currentXSL,
        complete: function () {
            LoadHomeNewsWidget(selector);
            var itemDate;
            jQuery(selector + " .RSSDate").each(function () {

                var tmpstr = jQuery(this).text().replace(/gmt|,/g, "");
                //alert(tmpstr);
                itemDate = Date.parse(tmpstr);
                itemDate = new Date(itemDate);
                //alert(itemDate);

                if (itemDate > new Date()) {
                    jQuery(jQuery(this).parent()).hide();
                }
                jQuery(this).text(itemDate.toString("dd-MM-yyyy"));
            });
        }
    });
}
//esto es para los rss 2/nov/2018 //
function RenderRSSWidget(selector, currentXML, currentXSL) {
    if ($(selector).length == 0)
        return;
    $(selector).transform({
        xml: currentXML, xsl: currentXSL,
        complete: function () {
			      //HAS-1097 - Si es necesario implementar exactamente cuando se renderiza las noticias
            //window.SetupAccessFix !== undefined && SetupAccessFix();
			FixLinksRepetidosSlickVerMas();
            //LoadHomeNewsWidget(selector);
            LoadHomeNewsWidgetSlick(selector);
            var itemDate;
            $(selector + " .RSSDate").each(function () {
                var tmpstr = $(this).text().replace(/gmt|,/g, "");
                itemDate = Date.parse(tmpstr);
                itemDate = new Date(itemDate);
                if (itemDate > new Date()) {
                    $($(this).parent()).hide();
                }
                $(this).text(itemDate.toString("dd-MM-yyyy"));
            });
        }
    });
}
function RenderWidget(selector, currentXML, currentXSL) {
    jQuery(selector).transform({
        xml: currentXML, xsl: currentXSL,
        complete: function () { }
    });
}


function displayInWidget(selector, attr, URL) {
    jQuery(selector).attr(attr, URL);
}
///////////////////////////////////////////////////
//////////////////////////////////////////////////

function LoadHomeNewsWidgetSlick(selector) {
    var $RSSWidget = "#" + jQuery(selector).attr("id");
    $($RSSWidget).find(".noticiasticker").slick({
        dots: false,
        infinite: true,
        speed: 800,
        slidesToShow: 3,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 3000,
        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 1,
                }
            },
            {
                breakpoint: 800,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 1
                }
            },
            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1
                }
            }
            // You can unslick at a given breakpoint now by adding:
            // settings: "unslick"
            // instead of a settings object
        ]
    });
}


//////////////////////////////////////////////////
function LoadHomeNewsWidget(selector) {
    var $RSSWidget = "#" + jQuery(selector).attr("id");
    $($RSSWidget).vTicker({
        speed: 1000,
        pause: 8000,
        showItems: 4,
        animation: 'fade',
        mousePause: true,
        height: 500,
        direction: 'up'
    });
    jQuery(".rssWidgetNext").click(function (event) {
        event.preventDefault();
        var $vTickerID = $(this).parent().find('div[id^=rssWidget]').attr("id");
        //$($RSSWidget).vTicker('next', { animate: true });
        $("#" + $vTickerID).vTicker('next', { animate: true });
    });
    /*jQuery(".rssWidgetPrev,.rssWidgetNext").hover(function ()
    {
        $($RSSWidget).vTicker('pause', true);
    },	function ()
        {
            $($RSSWidget).vTicker('pause', false);
    });*/
    jQuery(".rssWidgetPrev").click(function (event) {
        event.preventDefault();
        var $vTickerID = $(this).parent().find('div[id^=rssWidget]').attr("id");
        //$($RSSWidget).vTicker('prev', { animate: true });
        $("#" + $vTickerID).vTicker('prev', { animate: true });
    });
}
/////////////////////////////////

function SetupFontResize() {
    jQuery(".resetFont").click(function () {
        ResetFont(originalFontSize);
        return false;
    });
    // Increase Font Size
    jQuery(".increaseFont").click(function () {
        IncreaseFont(max);
        return false;
    });
    // Decrease Font Size
    jQuery(".decreaseFont").click(function () {
        DecreaseFont(min);
        return false;
    });
    ResizeFont();
}



function DecreaseFont(min) {
    var val = GetResizeFontCookie();
    if (val > min) {
        ChangeFont(0.85);
        SetResizeFontCookie(val - 1);
    }
}
function IncreaseFont(max) {
    var val = GetResizeFontCookie();
    if (val < max) {
        ChangeFont(1.15);
        SetResizeFontCookie(val + 1);
    }
}
function ChangeFont(rate) {
    jQuery('.HASBreadCrumbs').css('font-size', parseFloat(jQuery('.HASBreadCrumbs').css('font-size'), 10) * rate);
    jQuery('.WordSection1 h1').css('font-size', parseFloat(jQuery('.WordSection1 h1').css('font-size'), 10) * rate);
    jQuery('.WordSection1 h1 a').css('font-size', parseFloat(jQuery('.WordSection1 h1 a').css('font-size'), 10) * rate);
    jQuery('.WordSection1 h2').css('font-size', parseFloat(jQuery('.WordSection1 h2').css('font-size'), 10) * rate);
    jQuery('.WordSection1 h2 a').css('font-size', parseFloat(jQuery('.WordSection1 h2 a').css('font-size'), 10) * rate);
    jQuery('.WordSection1 h3').css('font-size', parseFloat(jQuery('.WordSection1 h3').css('font-size'), 10) * rate);
    jQuery('.WordSection1 h3 a').css('font-size', parseFloat(jQuery('.WordSection1 h3 a').css('font-size'), 10) * rate);
    jQuery('.WordSection1 p').css('font-size', parseFloat(jQuery('.WordSection1 p').css('font-size'), 10) * rate);
    jQuery('.WordSection1 b').css('font-size', parseFloat(jQuery('.WordSection1 b').css('font-size'), 10) * rate);
    jQuery('.WordSection1 p span').css('font-size', parseFloat(jQuery('.WordSection1 p span').css('font-size'), 10) * rate);
    jQuery('.WordSection1 a').css('font-size', parseFloat(jQuery('.WordSection1 p').css('font-size'), 10) * rate);
    jQuery('.WordSection1 span :not(p span)').css('font-size', parseFloat(jQuery('.WordSection1 span :not(p span)').css('font-size'), 10) * rate);
    jQuery('.WordSection1 h1 span').css('font-size', parseFloat(jQuery('.WordSection1 h1 span').css('font-size'), 10) * rate);
    jQuery('.WordSection1 h2 span').css('font-size', parseFloat(jQuery('.WordSection1 h2 span').css('font-size'), 10) * rate);
    jQuery('.WordSection1 h3 span').css('font-size', parseFloat(jQuery('.WordSection1 h3 span').css('font-size'), 10) * rate);
    jQuery('.WordSection1 strong').css('font-size', parseFloat(jQuery('.WordSection1 strong').css('font-size'), 10) * rate);
    jQuery('.WordSection1 td').css('font-size', parseFloat(jQuery('.WordSection1 td').css('font-size'), 10) * rate);
    jQuery('.WordSection1 p.MsoNormal').css('font-size', parseFloat(jQuery('.WordSection1 td p').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv h1').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv h1').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv h1 a').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv h1 a').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv h2').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv h2').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv h2 a').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv h2 a').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv h3').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv h3').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv h3 a').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv h3 a').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv p').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv p').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv b').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv b').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv p span').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv p span').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv a').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv p').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv span :not(p span)').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv span :not(p span)').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv h1 span').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv h1 span').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv h2 span').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv h2 span').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv h3 span').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv h3 span').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv strong').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv strong').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv td').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv td').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv p.MsoNormal').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv td p').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv li').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv li').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv label').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv label').css('font-size'), 10) * rate);
    jQuery('.MainContentPlaceDiv input').css('font-size', parseFloat(jQuery('.MainContentPlaceDiv label').css('font-size'), 10) * rate);
}
function ResetFont(originalFontSize) {
    SetResizeFontCookie(0);
    jQuery('.HASBreadCrumbs').css('font-size', '');
    jQuery('.WordSection1 h1').css('font-size', '');
    jQuery('.WordSection1 h1 a').css('font-size', '');
    jQuery('.WordSection1 h2').css('font-size', '');
    jQuery('.WordSection1 h2 a').css('font-size', '');
    jQuery('.WordSection1 h3').css('font-size', '');
    jQuery('.WordSection1 h3 a').css('font-size', '');
    jQuery('.WordSection1 p').css('font-size', '');
    jQuery('.WordSection1 b').css('font-size', '');
    jQuery('.WordSection1 p span').css('font-size', '');
    jQuery('.WordSection1 a').css('font-size', '');
    jQuery('.WordSection1 span').css('font-size', '');
    jQuery('.WordSection1 strong').css('font-size', '');
    jQuery('.WordSection1 td').css('font-size', '');
    jQuery('.WordSection1 p.MsoNormal').css('font-size', '');
    jQuery('.MainContentPlaceDiv h1').css('font-size', '');
    jQuery('.MainContentPlaceDiv h1 a').css('font-size', '');
    jQuery('.MainContentPlaceDiv h2').css('font-size', '');
    jQuery('.MainContentPlaceDiv h2 a').css('font-size', '');
    jQuery('.MainContentPlaceDiv h3').css('font-size', '');
    jQuery('.MainContentPlaceDiv h3 a').css('font-size', '');
    jQuery('.MainContentPlaceDiv p').css('font-size', '');
    jQuery('.MainContentPlaceDiv b').css('font-size', '');
    jQuery('.MainContentPlaceDiv p span').css('font-size', '');
    jQuery('.MainContentPlaceDiv a').css('font-size', '');
    jQuery('.MainContentPlaceDiv span').css('font-size', '');
    jQuery('.MainContentPlaceDiv strong').css('font-size', '');
    jQuery('.MainContentPlaceDiv td').css('font-size', '');
    jQuery('.MainContentPlaceDiv p.MsoNormal').css('font-size', '');
    jQuery('.MainContentPlaceDiv li').css('font-size', '');
    jQuery('.MainContentPlaceDiv label').css('font-size', '');
    jQuery('.MainContentPlaceDiv input').css('font-size', '');
    //jQuery('.WordSection1 p').css('font-size', originalFontSize);
}
function ResizeFont() {
    var val = GetResizeFontCookie();
    if (val > 0) {
        for (i = 0; i < val; i++) {
            IncreaseFont(100);
        }
    }
    else if (val < 0) {
        for (i = 0; i > val; i--) {
            DecreaseFont(-100);
        }
    }
    SetResizeFontCookie(val);
}

function GetResizeFontCookie() {
    if (jQuery.cookie("fontresize") != null) {
        return parseInt(jQuery.cookie("fontresize"));
    }
    else {
        return 0;
    }
}

function SetResizeFontCookie(val) {
    jQuery.cookie("fontresize", val, { path: '/', expires: 2 })
}


function ColorChangeSetup() {
    var currentColor = GetColorChangeCookie();
    jQuery("head").append("<link rel='stylesheet' id='ColorChange' href='/css/cambio/" + currentColor + ".css'>");

    jQuery(".ColorChange").click(function () {
        var newColor = jQuery(this).attr("data-color");
        SetColorChangeCookie(newColor);
        $("#ColorChange").attr("href", "/css/cambio/" + newColor + ".css");
    });
}


function SetColorChangeCookie(val) {
    jQuery.cookie("colorchange", val, { path: '/', expires: 2 })
}

function GetColorChangeCookie() {
    var currentColor = jQuery.cookie("colorchange");
    if (currentColor != null) {
        return currentColor;
    }
    else {
        return "default";
    }
}
//Funcion para cuando el contenido de un modal es muy largo
jQuery(function () {
    var maxHeight = $(window).height() - 160;

    jQuery(".modal-body").css('max-height', maxHeight);
});


function AbrirAyudaBuscador() {

    $('#buscadorAyudaModal').modal('show');

}


//Funcion para cuando los tabs se exceden el ancho del contenedor
jQuery(document).ready(function () {

    if (jQuery(".htabs").length > 0) {
        var WordWidth = $(".WordSection1").width();

        $(".htabs ul").each(function () {
            var $currentUL = jQuery(this);
            var ulWidth = 0;
            var maxH = -1;
            $currentUL.find("li").each(function () {
                var $currentLI = $(this);
                var h = $currentLI.height();

                ulWidth = ulWidth + $currentLI.width();
                maxH = h > maxH ? h : maxH;
            });

            if (ulWidth > WordWidth) {
                $currentUL.parents(".htabs:first").addClass("htabsMobile");
            }

            if (maxH > 55) {
                $currentUL.css({ "padding-bottom": maxH + "px" });
                $currentUL.find("li a").css({ "height": maxH + "px" });
            }


        });
    }


    function InicializarBuscadorAsistente() {

        $("#busquedaAsistente").html(

            "<span class='tituloBusquedaAsistente'>" + "Digite la informaci&oacuten a consultar" + "</span>" +

            VerBusquedaSolicitud(true)
            +


            "<fieldset id='selectorDiario' class='hidden criteriosUlContainer'>  " +
            "<legend>El documento consultade atienda a:</legend>  " +
            "<label><input type='radio' style='accent-color: #000;' name='selectorDiarioRadio' value='gaceta'>Diario Oficial La Gaceta</label> " +
            "<br><label><input type='radio' style='accent-color: #000;' name='selectorDiarioRadio' value='boletin'>Bolet&iacute;n Judicial</label> " +
            "</fieldset> <br/> " + 


			"<div class='criteriosUlContainer'>" +
            "<p><strong>Criterios de b&uacute;squeda</strong></p>" +

            "<p><ul style='margin-left: 25px;'  class='no-well'>" +
            "	<li> N&uacute;mero de documento asignado</li>" +
            "	<li>N&uacute;mero de solicitud del portal Web </li>" +
            "	<li>Autor de la solicitud Web (correo electr&oacute;nico)</li>" +
            "	<li>Palabra clave</li>" +
            "	<li>Fecha</li>" +
            "</ul></p>" + 
			"<button class='btn btn-help' href='#' onclick='AbrirAyudaBuscador(); return false;'>"+
			"<img alt='imagen de estructura' src='/images/help.png' style='height: 16px;'/>"
			+"&iquest;Necesita ayuda?</button>"+
			"</div>"
           
            
        );

    }


    window.SetupAsistenteVirtual !== undefined && SetupAsistenteVirtual(InicializarBuscadorAsistente);

    //GoogleAnalytics
    window.SetupGoogleAnalytics !== undefined && SetupGoogleAnalytics(GTag);


});




/**/
function BuscarPorNumDocumento(prefix, sufix, idText) {
    var subsitioStr = (idText === 'GacetaGenericaInput') ? "?idsubsitio=" + idsubsitio : "";
    jQuery("input[id$=expresion]").val(prefix + jQuery("input[id$=" + idText + "]").val() + sufix);
    jQuery("form").eq(0).attr("action", "/buscador/default.aspx?iralprimero=true" + subsitioStr);
    jQuery("form").eq(0).submit();
}

function BuscarGenerica(idText) {
    var subsitioStr = (idText === 'GacetaGenericaInput') ? "?idsubsitio=" + idsubsitio : "";
    jQuery("input[id$=expresion]").val(jQuery("input[id$=" + idText + "]").val());
    jQuery("form").eq(0).attr("action", "/buscador/default.aspx" + subsitioStr);
    $("input[name=tipoBusqueda]").val("1");
    jQuery("form").eq(0).submit();
}




function fixBuscadorNumDoc(idBut, idText) {
    //Se elimina funcionalidad desde que se unifico los buscadores
    return;
}

function ApplyCSSChanges(id) {
    id = "#" + id + "_filter";

    jQuery(id).addClass('DataTableSearchContainer');
    jQuery(id).append('<div class="SearchIcnContainer"><span class="glyphicon glyphicon-search"></span></div>');

    //jQuery(id).each(function () {
    //    var text = $(this).text();
    //    $(this).text(text.replace('Buscar:', ''));
    //});

    jQuery(id).mouseover(function () {
        jQuery(id).addClass('SearchContainerExpanded');
        //alert(id);
    });

    jQuery(id).mouseleave(function () {
        jQuery(id).removeClass('SearchContainerExpanded');
        //alert(id + "sali");
    });
}

jQuery(window).scroll(function () {
    if (jQuery(window).width() < 768) {
        if (typeof (SectionBgRefresh) != 'undefined') {
            SectionBgRefresh();
        }
        return true;
    }
    var scroll = jQuery(window).scrollTop();
    var jQuerywindow = jQuery(window);


    if (scroll >= 75) {
        //jQuery("body").addClass("bodyPaddingTop");
        //jQuery(".header").addClass("headerActive");
        //jQuery(".PrincipalNav").addClass("PrincipalNavActive");
        jQuery(".ChatBtn").addClass("ChatBtnActive");
        //jQuery(".NavBarEdicion").addClass("NavBarEdicionActive");
    } else {
        //jQuery("body").removeClass("bodyPaddingTop");
        //jQuery(".header").removeClass("headerActive");
        //jQuery(".PrincipalNav").removeClass("PrincipalNavActive");
        jQuery(".ChatBtn").removeClass("ChatBtnActive");
        //jQuery(".NavBarEdicion").removeClass("NavBarEdicionActive");
    }
    if (typeof (SectionBgRefresh) != 'undefined') {
        SectionBgRefresh();
    }
});


function CloseAll() {
    $(".DivContenidos").removeClass("DivContenidosActive");
    $(".DivAlcances").removeClass("DivAlcancesActive");
    $(".DivResuladosBusquedaGaceta").removeClass("DivContenidosActive");
}

function SetContenidoCentral() {
    var AlgoAbierto = jQuery(".DivContenidosActive,.DivAlcancesActive").length > 0;
    if (AlgoAbierto) {
        $(".ContenidoCentral").addClass("ContenidoCentralAbierto");
    } else {
        $(".ContenidoCentral").removeClass("ContenidoCentralAbierto");
    }
};


function ToggleSection(selector, activeClass) {
    CloseAll();
    jQuery(".BotonNavBar").removeClass("BotonNavBarActive");

    if (jQuery(selector).hasClass(activeClass)) {
        $(selector).removeClass(activeClass);
    } else {
        $(selector).addClass(activeClass);
    }
    SetContenidoCentral();
    setTimeout(function () {
        jQuery(window).resize();
    },
        100);
}

//jQuery(".").click(function () {
//    $(".DivResuladosBusquedaGaceta").toggleClass("DivResuladosBusquedaGacetaActive");
//});
jQuery(".AbrirContenidos").click(function () {
    ToggleSection(".DivContenidos", "DivContenidosActive");
    jQuery(this).addClass("BotonNavBarActive");
});


jQuery(".AbrirAlcances").click(function () {
    ToggleSection(".DivAlcances", "DivAlcancesActive");
    jQuery(this).addClass("BotonNavBarActive");
});





/*------BUSCADOR DIALOG-------*/

var diario = "";//RegExp(/\/boletin\//).test(location.href) ? "boletin" : "gaceta";
var idsubsitio = -1;//RegExp(/\/boletin\//).test(location.href) ? "2" : "678";
var onlyNumbersRegex = new RegExp("^[0-9]+$");
var IDSUBSITIOGACETA = 678;
var GACETA = "gaceta";
var IDSUBSITIOBOLETIN = 2;
var BOLETIN = "boletin";

jQuery(".LabelSearchContainer").click(function () {
    ShowSearchDialog();
});

function ShowSearchDialog() {
    jQuery("#SearchDialog").modal();
    setTimeout(
        function () {
            jQuery("#GacetaGenericaInput").focus();
        }
        , 500);
}

jQuery("#SearchDialog .tab a").click(function (e) {
    e.preventDefault;
    var $this = jQuery(this);
    jQuery("#SearchDialog .tab.active").removeClass("active");
    $this.parents(".tab").addClass("active");
    var busquedaTitulo = "";

    //jQuery("#GacetasAnterioresDatePicker").hide();

    jQuery("#comunicadoBoletin").hide();

    $(".cajaBusqueda").show(); //todas menos la nueva

    $("#busquedaAsistente").hide();

    switch ($this.data("searchtype")) {
        case "general":
            idsubsitio = -1;
            busquedaTitulo = "Buscar en el Sitio de Imprenta Nacional";
            jQuery("#SearchGacetaType input[value='generica']").prop('checked', true);
            jQuery("#SearchGacetaType ").hide();
            break;
        case "gaceta":
            idsubsitio = IDSUBSITIOGACETA;
            diario = GACETA;
            jQuery("#SearchGacetaType ").show();
            busquedaTitulo = "Buscar en Gaceta";
            break;
        case "boletinJudicial":
            idsubsitio = IDSUBSITIOBOLETIN;
            diario = BOLETIN;
            jQuery("#SearchGacetaType ").show();
            jQuery("#comunicadoBoletin").show();
            busquedaTitulo = "Buscador hist&oacute;rico Bolet&iacute;n Judicial";
            break;
        case "busquedaAsistente":

            jQuery("#SearchGacetaType ").hide();
            $(".cajaBusqueda").hide();
            $("#busquedaAsistente").show();
            /*
            $("#busquedaAsistente").html(
                VerBusquedaSolicitud(true)
            );
            */
            busquedaTitulo = ""; //todo desde el item del Asistente
            break;

    }
    jQuery("#SearchGacetaType").change();
    jQuery(".searchContainer .busquedaTitulo").html(busquedaTitulo);

    if (busquedaTitulo == "")
        jQuery(".searchContainer .busquedaTitulo").hide();
    else
        jQuery(".searchContainer .busquedaTitulo").show();
});


jQuery("#SearchDialog .tab a:first").click();




/*Buscar OTRAS Gacetas*/

if (typeof (GacetaDate) != 'undefined') {
    jQuery("#GacetasAnterioresDatePicker").val(GacetaDate);
}

jQuery("#SearchGacetaType").change(function () {
    var TipoBusqueda = jQuery(this).find("input[name='SearchGacetaType']:checked").val();
    //console.log(TipoBusqueda);

    if (TipoBusqueda == "historica") {
        jQuery("#GacetasAnterioresDatePicker").show();
        jQuery("#GacetaGenericaInput").hide();

    } else {
        jQuery("#GacetasAnterioresDatePicker").hide();
        jQuery("#GacetaGenericaInput").show();
    }

    if (TipoBusqueda == "RP") {
        //alert(TipoBusqueda);
        $("#MensajeRPSpan").show();
    }
    else {
        $("#MensajeRPSpan").hide();
    }



    /*
    jQuery(".SearchInputLI").hide();
    jQuery("#" + TipoBusqueda.attr("class") + "LI").show();
    if (TipoBusqueda.attr("class") == "historica") {
        //jQuery("#GacetasAnterioresDatePicker").datepicker("show");
    }*/
})

jQuery("#SearchGacetaType").change();

jQuery("#BuscadorGacetasAnterioresDiv").show();


jQuery("#BuscarGacetasAnterioresButton").click(function (e) {
    e.preventDefault();
    var tipoBusqueda = jQuery("#SearchGacetaType input[name='SearchGacetaType']:checked").val();

    var idText = "GacetaGenericaInput";
    switch (tipoBusqueda) {
        case "historica":
            var SelectedGacetaDate = jQuery("#GacetasAnterioresDatePicker").val();
            if (SelectedGacetaDate != '') {
                window.location = "/" + diario + "/?date=" + SelectedGacetaDate;
            }
            break;
        case "generica":
            BuscarGenerica(idText);
            break;
        case "IN":
            BuscarPorNumDocumento("(IN", ")", idText)
            break;
        case "RP":
            BuscarPorNumDocumento("RP", "", idText)
            break;
    }
});

function BuscarPorNumDocumento(prefix, sufix, idText) {
    //var subsitioStr = (idText === 'GacetaGenericaInput') ? "&idsubsitio=" + idsubsitio : "";
    var subsitioStr = (idsubsitio > -1) ? "?idsubsitio=" + idsubsitio : "";
    jQuery("input[id$=expresion]").val(prefix + jQuery("input[id$=" + idText + "]").val() + sufix);
    jQuery("form").eq(0).attr("action", "/buscador/default.aspx?iralprimero=true" + subsitioStr);
    jQuery("#__VIEWSTATE,#__EVENTVALIDATION,#__EVENTTARGET,#__EVENTARGUMENT").remove();
    jQuery("form").eq(0).submit();
}

window._forzarBusquedaGenerica = false;
function BuscarGenerica(idText) {
    //var subsitioStr = (idText === 'GacetaGenericaInput') ? "?idsubsitio=" + idsubsitio : "";
    var subsitioStr = (idsubsitio > -1) ? "?idsubsitio=" + idsubsitio : "";
    jQuery("#__VIEWSTATE,#__EVENTVALIDATION,#__EVENTTARGET,#__EVENTARGUMENT").remove();
    jQuery("input[id$=expresion]").val(jQuery("input[id$=" + idText + "]").val());
    jQuery("form").eq(0).attr("action", "/buscador/default.aspx" + subsitioStr);
    jQuery("form").eq(0).submit();
	window._forzarBusquedaGenerica = true;
	console.log("Set Forzar Generica");

    //evitar que al hacer back en lugar del texto del bot�n 
    //diga el criterio
    //jQuery("input[id$=expresion]").val("Buscar");
    
}

var _daysOfWeekDisabled = "0,6";
//var habilitarGacetaFinDeSemana = true;

if (typeof (habilitarGacetaFinDeSemana) != 'undefined' && habilitarGacetaFinDeSemana == 1) {
    _daysOfWeekDisabled = "";
}


function fixesMuseoDiarios() {
    let UrlSitioPrincipal = "https://www.imprentanacional.go.cr";
    $("#MenuPrincipalContainer .navbar-nav")
        .prepend(`<li class="dropdown mega-dropdown"><a href="/"><span class="menuTextContainer">Volver a sitio principal</span></a></li>`);
    $(".navbar-nav a[href^='/'], a.logo_imprenta_footer, a.logo_imprenta")
        .each(function () {
            let $this = $(this);
            $this.attr("href", `${UrlSitioPrincipal}${$this.attr("href")}`);
        });
    /**/
    $(".header").css({
        background: "url('/images/contextual/buscadorGacetasHistoricas.jpg')",
        "background-size": "cover",
        height: "150px",
    }).removeClass("hidden-xs");

    $(".HeaderContainer").empty();
    $(".HeaderContainer").css({ position: "relative", height: "100%" });
    $(".HeaderContainer")
        .append("<div class='contextualText'>Museo de Diarios Oficiales</div>")
        .append("<a style='position: absolute;right: 10%;bottom: 15px;padding: 5px 50px !important;' class='hidden-xs btn btn-primary volversalas' href='/salas/'>Salas</a>");
    $(".contextualText").css({
        bottom: "0",
        position: "absolute",
        background: "rgba(0,0,0,0.5)",
        color: "white",
        "font-size": "24px",
        padding: "10px 20px",
        left: "10%",
        "text-align": "center"
    });
    /**/
}

jQuery(function () {
    var currentDatePickerOptions = {
        format: "dd/mm/yyyy",
        todayBtn: true,
        language: "es",
        autoclose: true,
        todayHighlight: true,
        showOnFocus: true,
        calendarWeeks: true,
        daysOfWeekDisabled: _daysOfWeekDisabled,
        endDate: "0d"
    }
	
    if (typeof $.fn.datepicker != "undefined") {
		jQuery("#GacetasAnterioresDatePicker")
			.datepicker(currentDatePickerOptions);
    }	
	


    jQuery("#expresion,#botonBuscar,#expresionMobile,#BuscarButtonMobile,#ctl00_CriterioBusquedaTextBox").focus(function (e) {
        e.preventDefault();
        ShowSearchDialog();
    });

    IrABoletinEnGaceta();

});
/*END Buscar OTRAS Gacetas*/
/*------END BUSCADOR DIALOG-------*/;
var _optionChatList = {};

function ToggleChatBot() {

    var strDateActive = window.sessionStorage.getItem('dateActiveChatBot');

    var dateNow = new Date();
    var dateActive = new Date(strDateActive);

    if (strDateActive != null && dateNow > dateActive) {
        window.sessionStorage.removeItem('itemChat');
    }

    if (!MostrarChatHome()) {
        var $chat = $('#ChatMessageDiv');

        if ($chat.hasClass("active")) {
            $chat.removeClass("active");
        } else {
            $chat.addClass("active");
            LoadChatList();
        }
    }
}

function MostrarChatHome() {
    var result = false;

    var itemChat = window.sessionStorage.getItem('itemChat');

    if (itemChat == null) {
        $('#ChatHome').addClass("active");
        result = true;
    }

    return result;
}

var ultimoItemChat;

function LoadChatList() {
    var itemChat = window.sessionStorage.getItem('itemChat');

    var item = null;

    if (itemChat == '0') {
        item = {
            id: 0,
            back: null,
            items: _optionChatList,
            pregunta: 'SELECCIONE SU CONSULTA',
            respuesta: '',
            url: ''
        }
    } else {
        for (var i = 0; i < _optionChatList.length; i++) {

            item = FindNode(_optionChatList[i], 'id', itemChat);

            if (item != false) {
                ultimoItemChat = item;
                i = _optionChatList.length;
            }
        }
    }

    PrintChatList(item);
}

function PrintChatList(item) {
    var $ChatList = $('#ChatList');
    $ChatList.empty();

    var previousNode = (item.back == undefined || item.back == null) ? '' :
        `onclick="ChangeOptionChat('${item.back}', '')"`
    var previousIcon = (item.back == undefined || item.back == null) ? '' :
        '<i class="fa fa-chevron-circle-left" aria-hidden="true"></i>';

    $('#LinkPrevios').remove();
    $('#DatosIntermedios').remove();

    $ChatList.before(
        `<a class="notClick list-group-item active chatTitle" id="LinkPrevios" ${previousNode}>${previousIcon} ${item.pregunta}</a>`
    );

    if (item.items != undefined && item.items.length > 0) {
        item.items.forEach(function (element) {
            $ChatList.append(
                `<a class="notClick list-group-item" onclick="ChangeOptionChat('${element.id}', '${element.url}')">
                <i class="fa fa-caret-right" aria-hidden="true"></i>
                ${element.pregunta}
                </a>`
            );
        });
    }
    else {

        item.respuesta = item.respuesta.split("\n").join("<br/>");

        $ChatList.before(
            `<div id="DatosIntermedios"> 
                <div class="DatosIntermediosContenedor">
					${item.respuesta} <br><br>
                    <a onclick="DarPorAtendidoAsistente(this)">Dar por atendido</a>
				</div>
                <hr>
                <button class="btn btn-link" onclick="MostrarFormulario()">¿Encontró  lo que buscaba?</button>
            </div>`
        );
    }
}

function MostrarFormulario() {
    event.preventDefault();

    var $datos = $('#DatosIntermedios');
    $datos.empty();

    //<input type="hidden" name="IDTipoFormulario" class="IDTipoFormulario" value="1"/>

    $datos.append(
        `<form id='FormularioAsistenteVirtual' class='mt-4'>
            <div class="h3">Formulario de consulta</div>
            <input type="hidden" name="doEncoding" value="false"/>

            <div class="form-horizontalX">
                 <label for="IDTipoFormulario" class="col-sm-2X control-label">Área</label>
                 <select id="IDTipoFormulario" name="IDTipoFormulario" class="form-control col-sm-10X IDTipoFormulario"></select>
            </div>

            <div>
				<label for="nombre">Nombre completo:</label><br>
				<input type="text" id="nombre" name="nombre" required="required" value="" class="form-control nombreAsistente">
			</div>
			<div>
				<label for="email">Correo:</label><br>
				<input type="email" id="email" required="required" class="form-control emailAsistente" name="email" placeholder="ejemplo@dominio.com" value="">
            </div>
			<div>
				<label for="consulta">Consulta:</label><br>
				<textarea required="required" name="consulta" id="consulta" class="form-control" placeholder="Ingrese su consulta"></textarea>
            </div>
			<div class="AsistenteBtnFlex">
				<input type="submit" value="Enviar" class="btn btn-primary" onclick="EnviarFormularioAsistenteVirtual(this)">
                <a aria-label="Chat en WhatsApp" id="linkWhatsApp" target="_blank" class="btn btn-primary AsistenteBtnFlex" href="setraedelServer">
					<svg xmlns="http://www.w3.org/2000/svg" height="16" width="14" viewBox="0 0 448 512">
						<!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2023 Fonticons, Inc.-->
						<path fill="#ffffff" d="M380.9 97.1C339 55.1 283.2 32 223.9 32c-122.4 0-222 99.6-222 222 0 39.1 10.2 77.3 29.6 111L0 480l117.7-30.9c32.4 17.7 68.9 27 106.1 27h.1c122.3 0 224.1-99.6 224.1-222 0-59.3-25.2-115-67.1-157zm-157 341.6c-33.2 0-65.7-8.9-94-25.7l-6.7-4-69.8 18.3L72 359.2l-4.4-7c-18.5-29.4-28.2-63.3-28.2-98.2 0-101.7 82.8-184.5 184.6-184.5 49.3 0 95.6 19.2 130.4 54.1 34.8 34.9 56.2 81.2 56.1 130.5 0 101.8-84.9 184.6-186.6 184.6zm101.2-138.2c-5.5-2.8-32.8-16.2-37.9-18-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18-17.6 21.8-3.2 3.7-6.5 4.2-12 1.4-32.6-16.3-54-29.1-75.5-66-5.7-9.8 5.7-9.1 16.3-30.3 1.8-3.7 .9-6.9-.5-9.7-1.4-2.8-12.5-30.1-17.1-41.2-4.5-10.8-9.1-9.3-12.5-9.5-3.2-.2-6.9-.2-10.6-.2-3.7 0-9.7 1.4-14.8 6.9-5.1 5.6-19.4 19-19.4 46.3 0 27.3 19.9 53.7 22.6 57.4 2.8 3.7 39.1 59.7 94.8 83.8 35.2 15.2 49 16.5 66.6 13.9 10.7-1.6 32.8-13.4 37.4-26.4 4.6-13 4.6-24.1 3.2-26.4-1.3-2.5-5-3.9-10.5-6.6z"/>
					</svg>
					WhatsApp
				<a/>
            </div>
			<div class="AsistenteBtnFlex">
				<a href="/OtrasFormasDeContacto.aspx" class="btn btn-info">Otras formas de contacto<a/>
                <a href="/ConsultasRecibidas.aspx" class="btn btn-info">Ver consultas anteriores<a/>
			</div>
        </form>
        <div id="MensajeDiv"></div>`
    );

    var tel = $(".TelWhatsAppHiddenField").val();
    debugger;
    $("#linkWhatsApp").attr("href", "https://web.whatsapp.com/send?phone=" + tel + "&text=Hola,%20me%20gustar%C3%ADa%20recibir%20informaci%C3%B3n");

    EjecutarPostAjax(
        "/App_HttpHandlers/MobileAppHandler.ashx?accion=GetObjetos&typeName=Formulario&asList=true",
        {}
    ).then((response) => {
        debugger;

        $.each(response.data, function (key, value) {
            $('#IDTipoFormulario')
                .append($('<option>', { value: value.IdTipoFormulario })
                    .text(value.Descripcion));
        });
        
    });

    


    $(".nombreAsistente").val(
        $(".UserNameAsistenteHiddenField").val()
    );

    $(".emailAsistente").val(
        $(".IdUserAsistenteHiddenField").val()
    );
}


function ChangeOptionChat(next, url) {

    //debugger;
    if (url != undefined && url != null && url != '' && url != 'null') {

        if (url.includes('?')) {
            url += '&chat=open';
        } else {
            url += '?chat=open';
        }

        window.location.href = url;
    } else {
        window.sessionStorage.setItem('itemChat', next);
        LoadChatList();
    }

    var now = new Date();
    now.setHours(now.getHours() + 1);

    window.sessionStorage.setItem('dateActiveChatBot', now);
}

function ChatToHome() {
    event.preventDefault();
    CloseChatHome();
    window.sessionStorage.removeItem('dateActiveChatBot');
    window.sessionStorage.setItem('itemChat', 0);
    ToggleChatBot();
}

function CloseChatHome() {
    ToggleChatBot();
    window.sessionStorage.removeItem('itemChat');
    $('#ChatHome').removeClass("active");
}

function TieneContenido(selector) {
    return $(selector).val().length > 0;
}

function GetPasosChatHastaActual()
{
    //debugger;

    var padre = ultimoItemChat;
    var idPadre = padre.back;

    var pasos = [ultimoItemChat.pregunta];

    while (idPadre > 0) {

        for (var i = 0; i < _optionChatList.length; i++) {
           
            padre = FindNode(_optionChatList[i], 'id', idPadre);

            if (padre != false) {
                idPadre = padre.back;

                pasos.push(padre.pregunta)
                i = _optionChatList.length;
            }
        }

    }

    pasos = pasos.reverse();

    for (var i = 0; i < pasos.length; i++) {
      //  pasos[i] = (i + 1) + ' ' + pasos[i]; //numerar
    }

    return pasos.join(" / ");
}

//Aqui se implementa el envio del formulario 
function EnviarFormularioAsistenteVirtual(boton) {
    var elBoton = $(boton);
   
    elBoton.prop("disabled", true);

    event.preventDefault();

    if (TieneContenido("#nombre") && TieneContenido("#email") && TieneContenido("#consulta")) {


        var data = $('#FormularioAsistenteVirtual').serializeObject();
        data["PasosChat"] = GetPasosChatHastaActual();
       
        debugger;
        //window.sessionStorage.setItem('itemChat', next);

        //data = {
        //    campo1: '',
        //    campo1: ''
        //}

        console.log(data);
        EjecutarPostAjax(_AppRoot + '/App_HttpHandlers/FormularioAsistenteVirtualHandler.ashx', data)
            .then((response) => {
                console.log(response);

                InformationMessage(response.data);
                CloseChatHome();

                $("#FormularioAsistenteVirtual").remove();

                return;

                $("#MensajeDiv").html(response.data
                    /* Marianela no quiso darle esto a los usuarios
                    +
                    '<br><br><a class="btn btn-primary" href="/controlpanel/adminFormularios/formularios.aspx?esVisitante=true">Ir a seguimiento<\a>'
                    */
                );
            }).catch(function(thisError){
				console.error(thisError);
			});
    }
    else {
        ErrorMessage("Todos los campos son requeridos");
		elBoton.prop("disabled", false);
    }
}

function DarPorAtendidoAsistente(boton) {
    var FORMULARIOASISTENTE = 1;

    var elBoton = $(boton);

    elBoton.prop("disabled", "disabled");

    event.preventDefault();


    var data = {};
    data["PasosChat"] = GetPasosChatHastaActual();
    data["IDTipoFormulario"] = FORMULARIOASISTENTE;
    data["darPorAtendido"] = "true";
    data["doEncoding"] = "false";
    
    data["consulta"] = ultimoItemChat.pregunta; //necesario en la vista ViewFormulariosRespuestaAsistente

    var valor;

    valor = $(".UserNameAsistenteHiddenField").val();
    data["nombre"] = valor ? valor : "n/a";

    valor = $(".IdUserAsistenteHiddenField").val();
    data["email"] = valor ? valor : "n/a";
    data["consulta"] = "n/a";

    //debugger;

        console.log(data);
        EjecutarPostAjax(_AppRoot + '/App_HttpHandlers/FormularioAsistenteVirtualHandler.ashx', data)
            .then((response) => {
                console.log(response);
                InformationMessage(response.data);
                CloseChatHome();

            });
    
}


var SetupAsistenteVirtual = function (callback) {
  //Cargar opciones CHAT
  //
  EjecutarPostAjax(
    "/App_HttpHandlers/MobileAppHandler.ashx?accion=getcatalogoasistentevirtual",
    {}
  ).then((response) => {
    _optionChatList = response.data;
    if (window.location.href.includes("chat=open")) {
      ToggleChatBot();
      }

      if (callback) {
          callback();
      }
  });

  $(".MenuDerechaContainer  a[href$='preguntas_frecuentes.aspx']").click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    ToggleChatBot();
  });
};
;
// -----------------------------------
// Slidebars
// Version 0.10.3
// http://plugins.adchsm.me/slidebars/
//
// Written by Adam Smith
// http://www.adchsm.me/
//
// Released under MIT License
// http://plugins.adchsm.me/slidebars/license.txt
//
// ---------------------
// Index of Slidebars.js
//
// 001 - Default Settings
// 002 - Feature Detection
// 003 - User Agents
// 004 - Setup
// 005 - Animation
// 006 - Operations
// 007 - API
// 008 - User Input

;( function ( $ ) {

	$.slidebars = function ( options ) {

		// ----------------------
		// 001 - Default Settings

		var settings = $.extend( {
			siteClose: true, // true or false - Enable closing of Slidebars by clicking on #sb-site.
			scrollLock: false, // true or false - Prevent scrolling of site when a Slidebar is open.
			disableOver: false, // integer or false - Hide Slidebars over a specific width.
			hideControlClasses: false // true or false - Hide controls at same width as disableOver.
		}, options );

		// -----------------------
		// 002 - Feature Detection

		var test = document.createElement( 'div' ).style, // Create element to test on.
		supportTransition = false, // Variable for testing transitions.
		supportTransform = false; // variable for testing transforms.

		// Test for CSS Transitions
		if ( test.MozTransition === '' || test.WebkitTransition === '' || test.OTransition === '' || test.transition === '' ) supportTransition = true;

		// Test for CSS Transforms
		if ( test.MozTransform === '' || test.WebkitTransform === '' || test.OTransform === '' || test.transform === '' ) supportTransform = true;

		// -----------------
		// 003 - User Agents

		var ua = navigator.userAgent, // Get user agent string.
		android = false, // Variable for storing android version.
		iOS = false; // Variable for storing iOS version.
		
		if ( /Android/.test( ua ) ) { // Detect Android in user agent string.
			android = ua.substr( ua.indexOf( 'Android' )+8, 3 ); // Set version of Android.
		} else if ( /(iPhone|iPod|iPad)/.test( ua ) ) { // Detect iOS in user agent string.
			iOS = ua.substr( ua.indexOf( 'OS ' )+3, 3 ).replace( '_', '.' ); // Set version of iOS.
		}
		
		if ( android && android < 3 || iOS && iOS < 5 ) $( 'html' ).addClass( 'sb-static' ); // Add helper class for older versions of Android & iOS.

		// -----------
		// 004 - Setup

		// Site container
		var $site = $( '#sb-site, .sb-site-container' ); // Cache the selector.

		// Left Slidebar	
		if ( $( '.sb-left' ).length ) { // Check if the left Slidebar exists.
			var $left = $( '.sb-left' ), // Cache the selector.
			leftActive = false; // Used to check whether the left Slidebar is open or closed.
		}

		// Right Slidebar
		if ( $( '.sb-right' ).length ) { // Check if the right Slidebar exists.
			var $right = $( '.sb-right' ), // Cache the selector.
			rightActive = false; // Used to check whether the right Slidebar is open or closed.
		}
				
		var init = false, // Initialisation variable.
		windowWidth = $( window ).width(), // Get width of window.
		$controls = $( '.sb-toggle-left, .sb-toggle-right, .sb-open-left, .sb-open-right, .sb-close' ), // Cache the control classes.
		$slide = $( '.sb-slide' ); // Cache users elements to animate.
		
		// Initailise Slidebars
		function initialise () {
			if ( ! settings.disableOver || ( typeof settings.disableOver === 'number' && settings.disableOver >= windowWidth ) ) { // False or larger than window size. 
				init = true; // true enabled Slidebars to open.
				$( 'html' ).addClass( 'sb-init' ); // Add helper class.
				if ( settings.hideControlClasses ) $controls.removeClass( 'sb-hide' ); // Remove class just incase Slidebars was originally disabled.
				css(); // Set required inline styles.
			} else if ( typeof settings.disableOver === 'number' && settings.disableOver < windowWidth ) { // Less than window size.
				init = false; // false stop Slidebars from opening.
				$( 'html' ).removeClass( 'sb-init' ); // Remove helper class.
				if ( settings.hideControlClasses ) $controls.addClass( 'sb-hide' ); // Hide controls
				$site.css( 'minHeight', '' ); // Remove minimum height.
				if ( leftActive || rightActive ) close(); // Close Slidebars if open.
			}
		}
		initialise();
		
		// Inline CSS
		function css() {
			// Site container height.
			$site.css( 'minHeight', '' );
			var siteHeight = parseInt( $site.css( 'height' ), 10 ),
			htmlHeight = parseInt( $( 'html' ).css( 'height' ), 10 );
			if ( siteHeight < htmlHeight ) $site.css( 'minHeight', $( 'html' ).css( 'height' ) ); // Test height for vh support..
			
			// Custom Slidebar widths.
			if ( $left && $left.hasClass( 'sb-width-custom' ) ) $left.css( 'width', $left.attr( 'data-sb-width' ) ); // Set user custom width.
			if ( $right && $right.hasClass( 'sb-width-custom' ) ) $right.css( 'width', $right.attr( 'data-sb-width' ) ); // Set user custom width.
			
			// Set off-canvas margins for Slidebars with push and overlay animations.
			if ( $left && ( $left.hasClass( 'sb-style-push' ) || $left.hasClass( 'sb-style-overlay' ) ) ) $left.css( 'marginLeft', '-' + $left.css( 'width' ) );
			if ( $right && ( $right.hasClass( 'sb-style-push' ) || $right.hasClass( 'sb-style-overlay' ) ) ) $right.css( 'marginRight', '-' + $right.css( 'width' ) );
			
			// Site scroll locking.
			if ( settings.scrollLock ) $( 'html' ).addClass( 'sb-scroll-lock' );
		}
		
		// Resize Functions
		$( window ).resize( function () {
			var resizedWindowWidth = $( window ).width(); // Get resized window width.
			if ( windowWidth !== resizedWindowWidth ) { // Slidebars is running and window was actually resized.
				windowWidth = resizedWindowWidth; // Set the new window width.
				initialise(); // Call initalise to see if Slidebars should still be running.
				if ( leftActive ) open( 'left' ); // If left Slidebar is open, calling open will ensure it is the correct size.
				if ( rightActive ) open( 'right' ); // If right Slidebar is open, calling open will ensure it is the correct size.
			}
		} );
		// I may include a height check along side a width check here in future.

		// ---------------
		// 005 - Animation

		var animation; // Animation type.

		// Set animation type.
		if ( supportTransition && supportTransform ) { // Browser supports css transitions and transforms.
			animation = 'translate'; // Translate for browsers that support it.
			if ( android && android < 4.4 ) animation = 'side'; // Android supports both, but can't translate any fixed positions, so use left instead.
		} else {
			animation = 'jQuery'; // Browsers that don't support css transitions and transitions.
		}

		// Animate mixin.
		function animate( object, amount, side ) {
			
			// Choose selectors depending on animation style.
			var selector;
			
			if ( object.hasClass( 'sb-style-push' ) ) {
				selector = $site.add( object ).add( $slide ); // Push - Animate site, Slidebar and user elements.
			} else if ( object.hasClass( 'sb-style-overlay' ) ) {
				selector = object; // Overlay - Animate Slidebar only.
			} else {
				selector = $site.add( $slide ); // Reveal - Animate site and user elements.
			}
			
			// Apply animation
			if ( animation === 'translate' ) {
				if ( amount === '0px' ) {
					removeAnimation();
				} else {
					selector.css( 'transform', 'translate( ' + amount + ' )' ); // Apply the animation.
				}

			} else if ( animation === 'side' ) {
				if ( amount === '0px' ) {
					removeAnimation();
				} else {
					if ( amount[0] === '-' ) amount = amount.substr( 1 ); // Remove the '-' from the passed amount for side animations.
					selector.css( side, '0px' ); // Add a 0 value so css transition works.
					setTimeout( function () { // Set a timeout to allow the 0 value to be applied above.
						selector.css( side, amount ); // Apply the animation.
					}, 1 );
				}

			} else if ( animation === 'jQuery' ) {
				if ( amount[0] === '-' ) amount = amount.substr( 1 ); // Remove the '-' from the passed amount for jQuery animations.
				var properties = {};
				properties[side] = amount;
				selector.stop().animate( properties, 400 ); // Stop any current jQuery animation before starting another.
			}
			
			// Remove animation
			function removeAnimation () {
				selector.removeAttr( 'style' );
				css();
			}
		}

		// ----------------
		// 006 - Operations

		// Open a Slidebar
		function open( side ) {
			// Check to see if opposite Slidebar is open.
			if ( side === 'left' && $left && rightActive || side === 'right' && $right && leftActive ) { // It's open, close it, then continue.
				close();
				setTimeout( proceed, 400 );
			} else { // Its not open, continue.
				proceed();
			}

			// Open
			function proceed() {
				if ( init && side === 'left' && $left ) { // Slidebars is initiated, left is in use and called to open.
					$( 'html' ).addClass( 'sb-active sb-active-left' ); // Add active classes.
					$left.addClass( 'sb-active' );
					animate( $left, $left.css( 'width' ), 'left' ); // Animation
					setTimeout( function () { leftActive = true; }, 400 ); // Set active variables.
				} else if ( init && side === 'right' && $right ) { // Slidebars is initiated, right is in use and called to open.
					$( 'html' ).addClass( 'sb-active sb-active-right' ); // Add active classes.
					$right.addClass( 'sb-active' );
					animate( $right, '-' + $right.css( 'width' ), 'right' ); // Animation
					setTimeout( function () { rightActive = true; }, 400 ); // Set active variables.
				}
			}
		}
			
		// Close either Slidebar
		function close( url, target ) {
			if ( leftActive || rightActive ) { // If a Slidebar is open.
				if ( leftActive ) {
					animate( $left, '0px', 'left' ); // Animation
					leftActive = false;
				}
				if ( rightActive ) {
					animate( $right, '0px', 'right' ); // Animation
					rightActive = false;
				}
			
				setTimeout( function () { // Wait for closing animation to finish.
					$( 'html' ).removeClass( 'sb-active sb-active-left sb-active-right' ); // Remove active classes.
					if ( $left ) $left.removeClass( 'sb-active' );
					if ( $right ) $right.removeClass( 'sb-active' );
					if ( typeof url !== 'undefined' ) { // If a link has been passed to the function, go to it.
						if ( typeof target === undefined ) target = '_self'; // Set to _self if undefined.
						window.open( url, target ); // Open the url.
					}
				}, 400 );
			}
		}
		
		// Toggle either Slidebar
		function toggle( side ) {
			if ( side === 'left' && $left ) { // If left Slidebar is called and in use.
				if ( ! leftActive ) {
					open( 'left' ); // Slidebar is closed, open it.
				} else {
					close(); // Slidebar is open, close it.
				}
			}
			if ( side === 'right' && $right ) { // If right Slidebar is called and in use.
				if ( ! rightActive ) {
					open( 'right' ); // Slidebar is closed, open it.
				} else {
					close(); // Slidebar is open, close it.
				}
			}
		}

		// ---------
		// 007 - API
		
		this.slidebars = {
			open: open, // Maps user variable name to the open method.
			close: close, // Maps user variable name to the close method.
			toggle: toggle, // Maps user variable name to the toggle method.
			init: function () { // Returns true or false whether Slidebars are running or not.
				return init; // Returns true or false whether Slidebars are running.
			},
			active: function ( side ) { // Returns true or false whether Slidebar is open or closed.
				if ( side === 'left' && $left ) return leftActive;
				if ( side === 'right' && $right ) return rightActive;
			},
			destroy: function ( side ) { // Removes the Slidebar from the DOM.
				if ( side === 'left' && $left ) {
					if ( leftActive ) close(); // Close if its open.
					setTimeout( function () {
						$left.remove(); // Remove it.
						$left = false; // Set variable to false so it cannot be opened again.
					}, 400 );
				}
				if ( side === 'right' && $right) {
					if ( rightActive ) close(); // Close if its open.
					setTimeout( function () {
						$right.remove(); // Remove it.
						$right = false; // Set variable to false so it cannot be opened again.
					}, 400 );
				}
			}
		};

		// ----------------
		// 008 - User Input
		
		function eventHandler( event, selector ) {
			event.stopPropagation(); // Stop event bubbling.
			event.preventDefault(); // Prevent default behaviour.
			if ( event.type === 'touchend' ) selector.off( 'click' ); // If event type was touch, turn off clicks to prevent phantom clicks.
		}
		
		// Toggle left Slidebar
		$( '.sb-toggle-left' ).on( 'touchend click', function ( event ) {
			eventHandler( event, $( this ) ); // Handle the event.
			toggle( 'left' ); // Toggle the left Slidbar.
		} );
		
		// Toggle right Slidebar
		$( '.sb-toggle-right' ).on( 'touchend click', function ( event ) {
			eventHandler( event, $( this ) ); // Handle the event.
			toggle( 'right' ); // Toggle the right Slidbar.
		} );
		
		// Open left Slidebar
		$( '.sb-open-left' ).on( 'touchend click', function ( event ) {
			eventHandler( event, $( this ) ); // Handle the event.
			open( 'left' ); // Open the left Slidebar.
		} );
		
		// Open right Slidebar
		$( '.sb-open-right' ).on( 'touchend click', function ( event ) {
			eventHandler( event, $( this ) ); // Handle the event.
			open( 'right' ); // Open the right Slidebar.
		} );
		
		// Close Slidebar
		$( '.sb-close' ).on( 'touchend click', function ( event ) {
			if ( $( this ).is( 'a' ) || $( this ).children().is( 'a' ) ) { // Is a link or contains a link.
				if ( event.type === 'click' ) { // Make sure the user wanted to follow the link.
					event.stopPropagation(); // Stop events propagating
					event.preventDefault(); // Stop default behaviour
					
					var link = ( $( this ).is( 'a' ) ? $( this ) : $( this ).find( 'a' ) ), // Get the link selector.
					url = link.attr( 'href' ), // Get the link url.
					target = ( link.attr( 'target' ) ? link.attr( 'target' ) : '_self' ); // Set target, default to _self if not provided
					
					close( url, target ); // Close Slidebar and pass link target.
				}
			} else { // Just a normal control class.
				eventHandler( event, $( this ) ); // Handle the event.
				close(); // Close Slidebar.
			}
		} );
		
		// Close Slidebar via site
		$site.on( 'touchend click', function ( event ) {
			if ( settings.siteClose && ( leftActive || rightActive ) ) { // If settings permit closing by site and left or right Slidebar is open.
				eventHandler( event, $( this ) ); // Handle the event.
				close(); // Close it.
			}
		} );
		
	}; // End Slidebars function.

} ) ( jQuery );;
jQuery(document).ready(function($){
	// browser window scroll (in pixels) after which the "back to top" link is shown
	var offset = 300,
		//browser window scroll (in pixels) after which the "back to top" link opacity is reduced
		offset_opacity = 1200,
		//duration of the top scrolling animation (in ms)
		scroll_top_duration = 700,
		//grab the "back to top" link
		$back_to_top = $('.backtotop');

	//hide or show the "back to top" link
	$(window).scroll(function(){
		( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
		if( $(this).scrollTop() > offset_opacity ) { 
			$back_to_top.addClass('cd-fade-out');
		}
	});

	//smooth scroll to top
	$back_to_top.on('click', function(event){
		event.preventDefault();
		$('body,html').animate({
			scrollTop: 0 ,
		 	}, scroll_top_duration
		);
	});

    //Volver al menu principal
	$(".backtomenu").click(function () {
	    event.preventDefault();
	    $(".MenuPrincipalContainer  a:first").focus();
	    $('html, body').animate({
	        scrollTop: $("#BackToMainMenu").offset().top
	    }, 2000);
	});

});;
!function($){$.transform=function(o){var createXmlObj=function(e){if(window.ActiveXObject||"ActiveXObject"in window){var t=new ActiveXObject("Microsoft.XMLDOM");return t.loadXML(e),t}return(new DOMParser).parseFromString(e,"text/xml")},call=function(f,o,tel,other){if($.isFunction(f)){var arg1=tel.html();if("JSON"==o.c.dataType.toUpperCase())try{arg1=eval("("+tel.text()+")")}catch(ex){arg1={error:"An error occurred while converting HTML to JSON"}}"XML"==o.c.dataType.toUpperCase()&&(arg1=createXmlObj(tel.html()));try{f.apply(o.c,[arg1,o.c.xslstr,o.c.xmlstr,o.c,other])}catch(ex){}}},t=this;t.c={cache:!1,async:!0,xsl:!1,xml:!1,xslstr:!1,xmlstr:!1,xslobj:!1,xmlobj:!1,xslParams:!1,error:!1,success:!1,complete:!1,island:!1,pass:!1,msg:!1,dataType:"html"},$.extend(t.c,o),o.msg&&$(o.el).html("string"==typeof o.msg?o.msg:$(o.msg).html());var id=function(e){var t=e+"_"+Math.round(999*Math.random());return 0===$("#"+t).length?t:id(e)},replaceref=function(e,t){t.c.xsl=t.c.xsl||"";var r="file:"==location.protocol&&(window.ActiveXObject||"ActiveXObject"in window)?"\\":"/",c=location.protocol+r+r+location.host,t=location.pathname.substring(0,location.pathname.lastIndexOf(r)+1)+t.c.xsl.substring(0,t.c.xsl.lastIndexOf("/")+1);if(e.substring(0,1)==r)return c+e;if(".."!=e.substring(0,2))return c+t+e;for(var l=0;-1!=e.indexOf("..");)e=e.substring(e.indexOf("..")+3),l+=1;for(var s=c+t.substring(0,t.length-1),o=0;o<l;o++)s=s.substring(0,s.lastIndexOf(r));return s+r+e},checkReady=function(l){if((l.c.xslstr||l.c.xslobj)&&(l.c.xmlstr||l.c.xmlobj)){var e,t=!1,r=$("<div>");if(!l.c.throwerror){if(l.c.island&&(!0===l.c.island&&(l.c.island="body"),l.c.xslid=id("xsl"),$(l.c.island).append("<div id='"+l.c.xslid+"' name='"+l.c.xslid+"' style='display:none;'>"+l.c.xslstr+"</div>"),l.c.xmlid=id("xml"),$(l.c.island).append("<div id='"+l.c.xmlid+"' name='"+l.c.xmlid+"' style='display:none;'>"+l.c.xmlstr+"</div>")),l.c.xslobj=l.c.xslobj||createXmlObj(l.c.xslstr),l.c.xmlobj=l.c.xmlobj||createXmlObj(l.c.xmlstr),window.ActiveXObject||"ActiveXObject"in window)try{(e=function(e,t){for(var r=t.selectNodes(e),c=0;c<r.length;c++)r[c].setAttribute("href",replaceref(r[c].getAttribute("href"),l))})("//xsl:include",l.c.xslobj),e("//xsl:import",l.c.xslobj),c=function(e,t){for(var r in e){var c="//xsl:param[@name='"+r+"']";try{var l=e[r];("boolean"==typeof l||isNaN(parseInt(l))&&l.indexOf("'")<0)&&(l="'"+l+"'");var s,o=t.selectSingleNode(c);null==o&&((s=t.createElement("xsl:param")).setAttribute("name",r),t.documentElement.insertBefore(s,t.selectSingleNode("//xsl:template")),o=t.selectSingleNode(c)),o.setAttribute("select",l)}catch(e){}}},l.c.xslParams&&(c(l.c.xslParams,l.c.xslobj),l.c.xslobj=createXmlObj(l.c.xslobj.xml)),r.empty().html(l.c.xmlobj.transformNode(l.c.xslobj))}catch(e){t=!0,call(l.c.error,l,r,e)}else try{var c,s=new XSLTProcessor;(c=function(e){for(var t in e)try{s.setParameter(null,t,e[t])}catch(e){}})(l.c.xslParams);var o=document.implementation.createDocument("","",null);s.importStylesheet(l.c.xslobj),r.empty().append(s.transformToFragment(l.c.xmlobj,o))}catch(e){t=!0,call(l.c.error,l,r,e)}return l.c.el&&r.html()&&$(l.c.el).html(r.html()),t||call(l.c.success,l,r),call(l.c.complete,l,r),r.html()}call(l.c.error,l,r,{message:"Bad XML or XSL call"})}},makeCall=function(r,e,c){"string"==typeof e&&(e={cache:!1,url:e,dataType:"xml",async:r.c.async,pass:r.c.pass}),e.complete=function(e,t){"success"==t?("XSL"==c?200==e.status?r.c.xslstr=e.responseText:(r.c.xslstr="error",r.c.throwerror=!0):200==e.status?r.c.xmlstr=e.responseText:(r.c.xmlstr="error",r.c.throwerror=!0),r.c.async&&checkReady(r)):r.c.threwError||(r.c.threwError=!0,call(r.c.error,r,$("<div>"+e.responseText+"</div>"),{message:"Error requesting file "+this.url}),call(r.c.complete,r,$("<div>"+e.responseText+"</div>")))},$.ajax(e)};if(t.c.xsl&&makeCall(t,o.xsl,"XSL"),t.c.xml&&makeCall(t,o.xml,"XML"),!t.c.async||t.c.xmlstr||t.c.xmlobj||t.c.xslstr||t.c.xslobj)return checkReady(t)},$.fn.transform=function(e){return this.each(function(){(e=e||{}).el=this;new $.transform(e)})}}(jQuery);;
/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
;
/*
  Vertical News Ticker 1.15

  Original by: Tadas Juozapaitis ( kasp3rito [eta] gmail (dot) com )
               http://www.jugbit.com/jquery-vticker-vertical-news-ticker/

  Forked/Modified by: Richard Hollis @richhollis - richhollis.co.uk
*/

(function($){

  var defaults = {
    speed: 700,
    pause: 4000,
    showItems: 1,
    mousePause: true,
    height: 0,
    animate: true,
    margin: 0,
    padding: 0,
    startPaused: false
  };

  var internal = { 

    moveUp: function(state, attribs) {    
      internal.animate(state, attribs, 'up');
    },

    moveDown: function(state, attribs){
      internal.animate(state, attribs, 'down');
    },

    animate: function(state, attribs, dir) {
      var height = state.itemHeight;
      var options = state.options;
      var el = state.element;
      var obj = el.children('ul');
      var selector = (dir === 'up') ? 'li:first' : 'li:last';

      el.trigger("vticker.beforeTick");
      
      var clone = obj.children(selector).clone(true);

      if(options.height > 0) height = obj.children('li:first').height();
      height += (options.margin) + (options.padding*2); // adjust for margins & padding

      if(dir==='down') obj.css('top', '-' + height + 'px').prepend(clone);

      if(attribs && attribs.animate) {
        if(state.animating) return;
        state.animating = true;
        var opts = (dir === 'up') ? {top: '-=' + height + 'px'} : {top: 0};
        obj.animate(opts, options.speed, function() {
            $(obj).children(selector).remove();
            $(obj).css('top', '0px');
            state.animating = false;
            el.trigger("vticker.afterTick");
          });
      } else {
        obj.children(selector).remove();
        obj.css('top', '0px');
        el.trigger("vticker.afterTick");
      }
      if(dir==='up') clone.appendTo(obj);
    },

    nextUsePause: function() {
      var state = $(this).data('state');
      var options = state.options;
      if(state.isPaused || state.itemCount < 2) return;
      methods.next.call( this, {animate:options.animate} );
    },

    startInterval: function() {
      var state = $(this).data('state');
      var options = state.options;
      var initThis = this;
      state.intervalId = setInterval(function(){ 
        internal.nextUsePause.call( initThis );
      }, options.pause);
    },

    stopInterval: function() {
      var state = $(this).data('state');
      if(!state) return;
      if(state.intervalId) clearInterval(state.intervalId);
      state.intervalId = undefined;
    },

    restartInterval: function() {
      internal.stopInterval.call(this);
      internal.startInterval.call(this);
    }
  };

  var methods = {

    init: function(options) {
      // if init called second time then stop first, then re-init
      methods.stop.call(this);
      // init
      var defaultsClone = jQuery.extend({}, defaults);
      var options = $.extend(defaultsClone, options);
      var el = $(this);
      var state = { 
        itemCount: el.children('ul').children('li').length,
        itemHeight: 0,
        itemMargin: 0,
        element: el,
        animating: false,
        options: options,
        isPaused: (options.startPaused) ? true : false,
        pausedByCode: false
      };
      $(this).data('state', state);

      el.css({overflow: 'hidden', position: 'relative'})
        .children('ul').css({position: 'absolute', margin: 0, padding: 0})
        .children('li').css({margin: options.margin, padding: options.padding});

      if(isNaN(options.height) || options.height === 0)
      {
        el.children('ul').children('li').each(function(){
          var current = $(this);
          if(current.height() > state.itemHeight)
            state.itemHeight = current.height();
        });
        // set the same height on all child elements
        el.children('ul').children('li').each(function(){
          var current = $(this);
          current.height(state.itemHeight);
        });
        // set element to total height
        var box = (options.margin) + (options.padding * 2);
        el.height(((state.itemHeight + box) * options.showItems) + options.margin);
      }
      else
      {
        // set the preferred height
        el.height(options.height);
      }

      var initThis = this;
      if(!options.startPaused) {
        internal.startInterval.call( initThis );
      }

      if(options.mousePause)
      {
        el.bind("mouseenter", function () {
          //if the automatic scroll is paused, don't change that.
          if (state.isPaused === true) return; 
          state.pausedByCode = true; 
          // stop interval
          internal.stopInterval.call( initThis );
          methods.pause.call( initThis, true );
        }).bind("mouseleave", function () {
          //if the automatic scroll is paused, don't change that.
          if (state.isPaused === true && !state.pausedByCode) return;
          state.pausedByCode = false; 
          methods.pause.call(initThis, false);
          // restart interval
          internal.startInterval.call( initThis );
        });
      }
    },

    pause: function(pauseState) {
      var state = $(this).data('state');
      if(!state) return undefined;
      if(state.itemCount < 2) return false;
      state.isPaused = pauseState;
      var el = state.element;
      if(pauseState) {
        $(this).addClass('paused');
        el.trigger("vticker.pause");
      }
      else {
        $(this).removeClass('paused');
        el.trigger("vticker.resume");
      }
    },

    next: function(attribs) { 
      var state = $(this).data('state');
      if(!state) return undefined;
      if(state.animating || state.itemCount < 2) return false;
      internal.restartInterval.call( this );
      internal.moveUp(state, attribs); 
    },

    prev: function(attribs) {
      var state = $(this).data('state');
      if(!state) return undefined;
      if(state.animating || state.itemCount < 2) return false;
      internal.restartInterval.call( this );
      internal.moveDown(state, attribs); 
    },

    stop: function() {
      var state = $(this).data('state');
      if(!state) return undefined;
      internal.stopInterval.call( this );
    },

    remove: function() {
      var state = $(this).data('state');
      if(!state) return undefined;
      internal.stopInterval.call( this );
      var el = state.element;
      el.unbind();
      el.remove();
    }
  };
 
  $.fn.vTicker = function( method ) {
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.vTicker' );
    }    
  };
})(jQuery);
;
/**
 * @version: 1.0 Alpha-1
 * @author: Coolite Inc. http://www.coolite.com/
 * @date: 2008-05-13
 * @copyright: Copyright (c) 2006-2008, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * @license: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/. 
 * @website: http://www.datejs.com/
 */
Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|aft(er)?|from|hence)/i,subtract:/^(\-|bef(ore)?|ago)/i,yesterday:/^yes(terday)?/i,today:/^t(od(ay)?)?/i,tomorrow:/^tom(orrow)?/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^mn|min(ute)?s?/i,hour:/^h(our)?s?/i,week:/^w(eek)?s?/i,month:/^m(onth)?s?/i,day:/^d(ay)?s?/i,year:/^y(ear)?s?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a(?!u|p)|p)/i},timezones:[{name:"UTC",offset:"-000"},{name:"GMT",offset:"-000"},{name:"EST",offset:"-0500"},{name:"EDT",offset:"-0400"},{name:"CST",offset:"-0600"},{name:"CDT",offset:"-0500"},{name:"MST",offset:"-0700"},{name:"MDT",offset:"-0600"},{name:"PST",offset:"-0800"},{name:"PDT",offset:"-0700"}]};
(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo,p=function(s,l){if(!l){l=2;}
return("000"+s).slice(l*-1);};$P.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;};$P.setTimeToNow=function(){var n=new Date();this.setHours(n.getHours());this.setMinutes(n.getMinutes());this.setSeconds(n.getSeconds());this.setMilliseconds(n.getMilliseconds());return this;};$D.today=function(){return new Date().clearTime();};$D.compare=function(date1,date2){if(isNaN(date1)||isNaN(date2)){throw new Error(date1+" - "+date2);}else if(date1 instanceof Date&&date2 instanceof Date){return(date1<date2)?-1:(date1>date2)?1:0;}else{throw new TypeError(date1+" - "+date2);}};$D.equals=function(date1,date2){return(date1.compareTo(date2)===0);};$D.getDayNumberFromName=function(name){var n=$C.dayNames,m=$C.abbreviatedDayNames,o=$C.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s||o[i].toLowerCase()==s){return i;}}
return-1;};$D.getMonthNumberFromName=function(name){var n=$C.monthNames,m=$C.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};$D.isLeapYear=function(year){return((year%4===0&&year%100!==0)||year%400===0);};$D.getDaysInMonth=function(year,month){return[31,($D.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};$D.getTimezoneAbbreviation=function(offset){var z=$C.timezones,p;for(var i=0;i<z.length;i++){if(z[i].offset===offset){return z[i].name;}}
return null;};$D.getTimezoneOffset=function(name){var z=$C.timezones,p;for(var i=0;i<z.length;i++){if(z[i].name===name.toUpperCase()){return z[i].offset;}}
return null;};$P.clone=function(){return new Date(this.getTime());};$P.compareTo=function(date){return Date.compare(this,date);};$P.equals=function(date){return Date.equals(this,date||new Date());};$P.between=function(start,end){return this.getTime()>=start.getTime()&&this.getTime()<=end.getTime();};$P.isAfter=function(date){return this.compareTo(date||new Date())===1;};$P.isBefore=function(date){return(this.compareTo(date||new Date())===-1);};$P.isToday=function(){return this.isSameDay(new Date());};$P.isSameDay=function(date){return this.clone().clearTime().equals(date.clone().clearTime());};$P.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;};$P.addSeconds=function(value){return this.addMilliseconds(value*1000);};$P.addMinutes=function(value){return this.addMilliseconds(value*60000);};$P.addHours=function(value){return this.addMilliseconds(value*3600000);};$P.addDays=function(value){this.setDate(this.getDate()+value);return this;};$P.addWeeks=function(value){return this.addDays(value*7);};$P.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,$D.getDaysInMonth(this.getFullYear(),this.getMonth())));return this;};$P.addYears=function(value){return this.addMonths(value*12);};$P.add=function(config){if(typeof config=="number"){this._orient=config;return this;}
var x=config;if(x.milliseconds){this.addMilliseconds(x.milliseconds);}
if(x.seconds){this.addSeconds(x.seconds);}
if(x.minutes){this.addMinutes(x.minutes);}
if(x.hours){this.addHours(x.hours);}
if(x.weeks){this.addWeeks(x.weeks);}
if(x.months){this.addMonths(x.months);}
if(x.years){this.addYears(x.years);}
if(x.days){this.addDays(x.days);}
return this;};var $y,$m,$d;$P.getWeek=function(){var a,b,c,d,e,f,g,n,s,w;$y=(!$y)?this.getFullYear():$y;$m=(!$m)?this.getMonth()+1:$m;$d=(!$d)?this.getDate():$d;if($m<=2){a=$y-1;b=(a/4|0)-(a/100|0)+(a/400|0);c=((a-1)/4|0)-((a-1)/100|0)+((a-1)/400|0);s=b-c;e=0;f=$d-1+(31*($m-1));}else{a=$y;b=(a/4|0)-(a/100|0)+(a/400|0);c=((a-1)/4|0)-((a-1)/100|0)+((a-1)/400|0);s=b-c;e=s+1;f=$d+((153*($m-3)+2)/5)+58+s;}
g=(a+b)%7;d=(f+g-e)%7;n=(f+3-d)|0;if(n<0){w=53-((g-s)/5|0);}else if(n>364+s){w=1;}else{w=(n/7|0)+1;}
$y=$m=$d=null;return w;};$P.getISOWeek=function(){$y=this.getUTCFullYear();$m=this.getUTCMonth()+1;$d=this.getUTCDate();return p(this.getWeek());};$P.setWeek=function(n){return this.moveToDayOfWeek(1).addWeeks(n-this.getWeek());};$D._validate=function(n,min,max,name){if(typeof n=="undefined"){return false;}else if(typeof n!="number"){throw new TypeError(n+" is not a Number.");}else if(n<min||n>max){throw new RangeError(n+" is not a valid value for "+name+".");}
return true;};$D.validateMillisecond=function(value){return $D._validate(value,0,999,"millisecond");};$D.validateSecond=function(value){return $D._validate(value,0,59,"second");};$D.validateMinute=function(value){return $D._validate(value,0,59,"minute");};$D.validateHour=function(value){return $D._validate(value,0,23,"hour");};$D.validateDay=function(value,year,month){return $D._validate(value,1,$D.getDaysInMonth(year,month),"day");};$D.validateMonth=function(value){return $D._validate(value,0,11,"month");};$D.validateYear=function(value){return $D._validate(value,0,9999,"year");};$P.set=function(config){if($D.validateMillisecond(config.millisecond)){this.addMilliseconds(config.millisecond-this.getMilliseconds());}
if($D.validateSecond(config.second)){this.addSeconds(config.second-this.getSeconds());}
if($D.validateMinute(config.minute)){this.addMinutes(config.minute-this.getMinutes());}
if($D.validateHour(config.hour)){this.addHours(config.hour-this.getHours());}
if($D.validateMonth(config.month)){this.addMonths(config.month-this.getMonth());}
if($D.validateYear(config.year)){this.addYears(config.year-this.getFullYear());}
if($D.validateDay(config.day,this.getFullYear(),this.getMonth())){this.addDays(config.day-this.getDate());}
if(config.timezone){this.setTimezone(config.timezone);}
if(config.timezoneOffset){this.setTimezoneOffset(config.timezoneOffset);}
if(config.week&&$D._validate(config.week,0,53,"week")){this.setWeek(config.week);}
return this;};$P.moveToFirstDayOfMonth=function(){return this.set({day:1});};$P.moveToLastDayOfMonth=function(){return this.set({day:$D.getDaysInMonth(this.getFullYear(),this.getMonth())});};$P.moveToNthOccurrence=function(dayOfWeek,occurrence){var shift=0;if(occurrence>0){shift=occurrence-1;}
else if(occurrence===-1){this.moveToLastDayOfMonth();if(this.getDay()!==dayOfWeek){this.moveToDayOfWeek(dayOfWeek,-1);}
return this;}
return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(dayOfWeek,+1).addWeeks(shift);};$P.moveToDayOfWeek=function(dayOfWeek,orient){var diff=(dayOfWeek-this.getDay()+7*(orient||+1))%7;return this.addDays((diff===0)?diff+=7*(orient||+1):diff);};$P.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths((diff===0)?diff+=12*(orient||+1):diff);};$P.getOrdinalNumber=function(){return Math.ceil((this.clone().clearTime()-new Date(this.getFullYear(),0,1))/86400000)+1;};$P.getTimezone=function(){return $D.getTimezoneAbbreviation(this.getUTCOffset());};$P.setTimezoneOffset=function(offset){var here=this.getTimezoneOffset(),there=Number(offset)*-6/10;return this.addMinutes(there-here);};$P.setTimezone=function(offset){return this.setTimezoneOffset($D.getTimezoneOffset(offset));};$P.hasDaylightSavingTime=function(){return(Date.today().set({month:0,day:1}).getTimezoneOffset()!==Date.today().set({month:6,day:1}).getTimezoneOffset());};$P.isDaylightSavingTime=function(){return(this.hasDaylightSavingTime()&&new Date().getTimezoneOffset()===Date.today().set({month:6,day:1}).getTimezoneOffset());};$P.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-10000).toString();return r.charAt(0)+r.substr(2);}else{r=(n+10000).toString();return"+"+r.substr(1);}};$P.getElapsed=function(date){return(date||new Date())-this;};if(!$P.toISOString){$P.toISOString=function(){function f(n){return n<10?'0'+n:n;}
return'"'+this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z"';};}
$P._toString=$P.toString;$P.toString=function(format){var x=this;if(format&&format.length==1){var c=$C.formatPatterns;x.t=x.toString;switch(format){case"d":return x.t(c.shortDate);case"D":return x.t(c.longDate);case"F":return x.t(c.fullDateTime);case"m":return x.t(c.monthDay);case"r":return x.t(c.rfc1123);case"s":return x.t(c.sortableDateTime);case"t":return x.t(c.shortTime);case"T":return x.t(c.longTime);case"u":return x.t(c.universalSortableDateTime);case"y":return x.t(c.yearMonth);}}
var ord=function(n){switch(n*1){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};return format?format.replace(/(\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S)/g,function(m){if(m.charAt(0)==="\\"){return m.replace("\\","");}
x.h=x.getHours;switch(m){case"hh":return p(x.h()<13?(x.h()===0?12:x.h()):(x.h()-12));case"h":return x.h()<13?(x.h()===0?12:x.h()):(x.h()-12);case"HH":return p(x.h());case"H":return x.h();case"mm":return p(x.getMinutes());case"m":return x.getMinutes();case"ss":return p(x.getSeconds());case"s":return x.getSeconds();case"yyyy":return p(x.getFullYear(),4);case"yy":return p(x.getFullYear());case"dddd":return $C.dayNames[x.getDay()];case"ddd":return $C.abbreviatedDayNames[x.getDay()];case"dd":return p(x.getDate());case"d":return x.getDate();case"MMMM":return $C.monthNames[x.getMonth()];case"MMM":return $C.abbreviatedMonthNames[x.getMonth()];case"MM":return p((x.getMonth()+1));case"M":return x.getMonth()+1;case"t":return x.h()<12?$C.amDesignator.substring(0,1):$C.pmDesignator.substring(0,1);case"tt":return x.h()<12?$C.amDesignator:$C.pmDesignator;case"S":return ord(x.getDate());default:return m;}}):this._toString();};}());
(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo,$N=Number.prototype;$P._orient=+1;$P._nth=null;$P._is=false;$P._same=false;$P._isSecond=false;$N._dateElement="day";$P.next=function(){this._orient=+1;return this;};$D.next=function(){return $D.today().next();};$P.last=$P.prev=$P.previous=function(){this._orient=-1;return this;};$D.last=$D.prev=$D.previous=function(){return $D.today().last();};$P.is=function(){this._is=true;return this;};$P.same=function(){this._same=true;this._isSecond=false;return this;};$P.today=function(){return this.same().day();};$P.weekday=function(){if(this._is){this._is=false;return(!this.is().sat()&&!this.is().sun());}
return false;};$P.at=function(time){return(typeof time==="string")?$D.parse(this.toString("d")+" "+time):this.set(time);};$N.fromNow=$N.after=function(date){var c={};c[this._dateElement]=this;return((!date)?new Date():date.clone()).add(c);};$N.ago=$N.before=function(date){var c={};c[this._dateElement]=this*-1;return((!date)?new Date():date.clone()).add(c);};var dx=("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),mx=("january february march april may june july august september october november december").split(/\s/),px=("Millisecond Second Minute Hour Day Week Month Year").split(/\s/),pxf=("Milliseconds Seconds Minutes Hours Date Week Month FullYear").split(/\s/),nth=("final first second third fourth fifth").split(/\s/),de;$P.toObject=function(){var o={};for(var i=0;i<px.length;i++){o[px[i].toLowerCase()]=this["get"+pxf[i]]();}
return o;};$D.fromObject=function(config){config.week=null;return Date.today().set(config);};var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n;}
if(this._nth!==null){if(this._isSecond){this.addSeconds(this._orient*-1);}
this._isSecond=false;var ntemp=this._nth;this._nth=null;var temp=this.clone().moveToLastDayOfMonth();this.moveToNthOccurrence(n,ntemp);if(this>temp){throw new RangeError($D.getDayName(n)+" does not occur "+ntemp+" times in the month of "+$D.getMonthName(temp.getMonth())+" "+temp.getFullYear()+".");}
return this;}
return this.moveToDayOfWeek(n,this._orient);};};var sdf=function(n){return function(){var t=$D.today(),shift=n-t.getDay();if(n===0&&$C.firstDayOfWeek===1&&t.getDay()!==0){shift=shift+7;}
return t.addDays(shift);};};for(var i=0;i<dx.length;i++){$D[dx[i].toUpperCase()]=$D[dx[i].toUpperCase().substring(0,3)]=i;$D[dx[i]]=$D[dx[i].substring(0,3)]=sdf(i);$P[dx[i]]=$P[dx[i].substring(0,3)]=df(i);}
var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n;}
return this.moveToMonth(n,this._orient);};};var smf=function(n){return function(){return $D.today().set({month:n,day:1});};};for(var j=0;j<mx.length;j++){$D[mx[j].toUpperCase()]=$D[mx[j].toUpperCase().substring(0,3)]=j;$D[mx[j]]=$D[mx[j].substring(0,3)]=smf(j);$P[mx[j]]=$P[mx[j].substring(0,3)]=mf(j);}
var ef=function(j){return function(){if(this._isSecond){this._isSecond=false;return this;}
if(this._same){this._same=this._is=false;var o1=this.toObject(),o2=(arguments[0]||new Date()).toObject(),v="",k=j.toLowerCase();for(var m=(px.length-1);m>-1;m--){v=px[m].toLowerCase();if(o1[v]!=o2[v]){return false;}
if(k==v){break;}}
return true;}
if(j.substring(j.length-1)!="s"){j+="s";}
return this["add"+j](this._orient);};};var nf=function(n){return function(){this._dateElement=n;return this;};};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$P[de]=$P[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de);}
$P._ss=ef("Second");var nthfn=function(n){return function(dayOfWeek){if(this._same){return this._ss(arguments[0]);}
if(dayOfWeek||dayOfWeek===0){return this.moveToNthOccurrence(dayOfWeek,n);}
this._nth=n;if(n===2&&(dayOfWeek===undefined||dayOfWeek===null)){this._isSecond=true;return this.addSeconds(this._orient);}
return this;};};for(var l=0;l<nth.length;l++){$P[nth[l]]=(l===0)?nthfn(-1):nthfn(l);}}());
(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'";}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx){return([mx[0],s.substring(mx[0].length)]);}else{throw new $P.Exception(s);}};},token:function(s){return function(s){return _.rtoken(new RegExp("^\s*"+s+"\s*"))(s);};},stoken:function(s){return _.rtoken(new RegExp("^"+s));},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=p.call(this,s);}catch(e){qx.push(rx[0]);s=rx[1];continue;}
break;}
return[qx,s];};},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s);}catch(e){return[rx,s];}
rx.push(r[0]);s=r[1];}
return[rx,s];};},optional:function(p){return function(s){var r=null;try{r=p.call(this,s);}catch(e){return[null,s];}
return[r[0],r[1]];};},not:function(p){return function(s){try{p.call(this,s);}catch(e){return[null,s];}
throw new $P.Exception(s);};},ignore:function(p){return p?function(s){var r=null;r=p.call(this,s);return[null,r[1]];}:null;},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++){rx.push(_.each(px[i],qx));}
return rx;},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=(cache[s]||rule.call(this,s));}catch(e){r=cache[s]=e;}
if(r instanceof $P.Exception){throw r;}else{return r;}};},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){r=null;}
if(r){return r;}}
throw new $P.Exception(s);};},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){throw new $P.Exception(s);}
rx.push(r[0]);s=r[1];}
return[rx,s];};},all:function(){var px=arguments,_=_;return _.each(_.optional(px));},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1){return px[0];}
return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=px[i].call(this,s);}catch(e){break;}
rx.push(r[0]);try{q=d.call(this,r[1]);}catch(ex){q=null;break;}
s=q[1];}
if(!r){throw new $P.Exception(s);}
if(q){throw new $P.Exception(q[1]);}
if(c){try{r=c.call(this,r[1]);}catch(ey){throw new $P.Exception(r[1]);}}
return[rx,(r?r[1]:s)];};},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]];};},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return(p instanceof Array?_.each(_.product(p.slice(0,-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c)));},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=(px.length==1);try{r=px[i].call(this,s);}catch(e){continue;}
rx=[[r[0]],r[1]];if(r[1].length>0&&!last){try{q=d.call(this,r[1]);}catch(ex){last=true;}}else{last=true;}
if(!last&&q[1].length===0){last=true;}
if(!last){var qx=[];for(var j=0;j<px.length;j++){if(i!=j){qx.push(px[j]);}}
p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1];}}
if(rx[1].length<best[1].length){best=rx;}
if(best[1].length===0){break;}}
if(best[0].length===0){return best;}
if(c){try{q=c.call(this,best[1]);}catch(ey){throw new $P.Exception(best[1]);}
best[1]=q[1];}
return best;};},forward:function(gr,fname){return function(s){return gr[fname].call(this,s);};},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]];};},process:function(rule,fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]];};},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min){throw new $P.Exception(s);}
return rx;};}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments);}else if(arguments[0]instanceof Array){args=arguments[0];}
if(args){for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();return rx;}}else{return op.apply(null,arguments);}};};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++){_[gx[i]]=_generator(_[gx[i]]);}
var _vector=function(op){return function(){if(arguments[0]instanceof Array){return op.apply(null,arguments[0]);}else{return op.apply(null,arguments);}};};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++){_[vx[j]]=_vector(_[vx[j]]);}}());(function(){var $D=Date,$P=$D.prototype,$C=$D.CultureInfo;var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++){if(ax[i]instanceof Array){rx=rx.concat(flattenAndCompact(ax[i]));}else{if(ax[i]){rx.push(ax[i]);}}}
return rx;};$D.Grammar={};$D.Translator={hour:function(s){return function(){this.hour=Number(s);};},minute:function(s){return function(){this.minute=Number(s);};},second:function(s){return function(){this.second=Number(s);};},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase();};},timezone:function(s){return function(){var n=s.replace(/[^\d\+\-]/g,"");if(n.length){this.timezoneOffset=Number(n);}else{this.timezone=s.toLowerCase();}};},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0]);};},month:function(s){return function(){this.month=(s.length==3)?"jan feb mar apr may jun jul aug sep oct nov dec".indexOf(s)/4:Number(s)-1;};},year:function(s){return function(){var n=Number(s);this.year=((s.length>2)?n:(n+(((n+2000)<$C.twoDigitYearMax)?2000:1900)));};},rday:function(s){return function(){switch(s){case"yesterday":this.days=-1;break;case"tomorrow":this.days=1;break;case"today":this.days=0;break;case"now":this.days=0;this.now=true;break;}};},finishExact:function(x){x=(x instanceof Array)?x:[x];for(var i=0;i<x.length;i++){if(x[i]){x[i].call(this);}}
var now=new Date();if((this.hour||this.minute)&&(!this.month&&!this.year&&!this.day)){this.day=now.getDate();}
if(!this.year){this.year=now.getFullYear();}
if(!this.month&&this.month!==0){this.month=now.getMonth();}
if(!this.day){this.day=1;}
if(!this.hour){this.hour=0;}
if(!this.minute){this.minute=0;}
if(!this.second){this.second=0;}
if(this.meridian&&this.hour){if(this.meridian=="p"&&this.hour<12){this.hour=this.hour+12;}else if(this.meridian=="a"&&this.hour==12){this.hour=0;}}
if(this.day>$D.getDaysInMonth(this.year,this.month)){throw new RangeError(this.day+" is not a valid value for days.");}
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone){r.set({timezone:this.timezone});}else if(this.timezoneOffset){r.set({timezoneOffset:this.timezoneOffset});}
return r;},finish:function(x){x=(x instanceof Array)?flattenAndCompact(x):[x];if(x.length===0){return null;}
for(var i=0;i<x.length;i++){if(typeof x[i]=="function"){x[i].call(this);}}
var today=$D.today();if(this.now&&!this.unit&&!this.operator){return new Date();}else if(this.now){today=new Date();}
var expression=!!(this.days&&this.days!==null||this.orient||this.operator);var gap,mod,orient;orient=((this.orient=="past"||this.operator=="subtract")?-1:1);if(!this.now&&"hour minute second".indexOf(this.unit)!=-1){today.setTimeToNow();}
if(this.month||this.month===0){if("year day hour minute second".indexOf(this.unit)!=-1){this.value=this.month+1;this.month=null;expression=true;}}
if(!expression&&this.weekday&&!this.day&&!this.days){var temp=Date[this.weekday]();this.day=temp.getDate();if(!this.month){this.month=temp.getMonth();}
this.year=temp.getFullYear();}
if(expression&&this.weekday&&this.unit!="month"){this.unit="day";gap=($D.getDayNumberFromName(this.weekday)-today.getDay());mod=7;this.days=gap?((gap+(orient*mod))%mod):(orient*mod);}
if(this.month&&this.unit=="day"&&this.operator){this.value=(this.month+1);this.month=null;}
if(this.value!=null&&this.month!=null&&this.year!=null){this.day=this.value*1;}
if(this.month&&!this.day&&this.value){today.set({day:this.value*1});if(!expression){this.day=this.value*1;}}
if(!this.month&&this.value&&this.unit=="month"&&!this.now){this.month=this.value;expression=true;}
if(expression&&(this.month||this.month===0)&&this.unit!="year"){this.unit="month";gap=(this.month-today.getMonth());mod=12;this.months=gap?((gap+(orient*mod))%mod):(orient*mod);this.month=null;}
if(!this.unit){this.unit="day";}
if(!this.value&&this.operator&&this.operator!==null&&this[this.unit+"s"]&&this[this.unit+"s"]!==null){this[this.unit+"s"]=this[this.unit+"s"]+((this.operator=="add")?1:-1)+(this.value||0)*orient;}else if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value){this.value=1;}
this[this.unit+"s"]=this.value*orient;}
if(this.meridian&&this.hour){if(this.meridian=="p"&&this.hour<12){this.hour=this.hour+12;}else if(this.meridian=="a"&&this.hour==12){this.hour=0;}}
if(this.weekday&&!this.day&&!this.days){var temp=Date[this.weekday]();this.day=temp.getDate();if(temp.getMonth()!==today.getMonth()){this.month=temp.getMonth();}}
if((this.month||this.month===0)&&!this.day){this.day=1;}
if(!this.orient&&!this.operator&&this.unit=="week"&&this.value&&!this.day&&!this.month){return Date.today().setWeek(this.value);}
if(expression&&this.timezone&&this.day&&this.days){this.day=this.days;}
return(expression)?today.add(this):today.set(this);}};var _=$D.Parsing.Operators,g=$D.Grammar,t=$D.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|@|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=$C.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++){px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));}
fn=_C[keys]=_.any.apply(null,px);}
return fn;};g.ctoken2=function(key){return _.rtoken($C.regexPatterns[key]);};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.m,g.s],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s;};}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")));};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s;};});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=s;};});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("second minute hour day week month year"),function(s){return function(){this.unit=s;};});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"");};});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter);};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return((g[$C.dateElementOrder]||g.mdy).call(this,s));};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt]){return g[fmt];}else{throw $D.Parsing.Exception(fmt);}}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s));}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact);});var _F={};var _get=function(f){return _F[f]=(_F[f]||g.format(f)[0]);};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++){rx.push(_get(fx[i]));}
return _.any.apply(null,rx);}else{return _get(fx);}};g._formats=g.formats(["\"yyyy-MM-ddTHH:mm:ssZ\"","yyyy-MM-ddTHH:mm:ssZ","yyyy-MM-ddTHH:mm:ssz","yyyy-MM-ddTHH:mm:ss","yyyy-MM-ddTHH:mmZ","yyyy-MM-ddTHH:mmz","yyyy-MM-ddTHH:mm","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","MMddyyyy","ddMMyyyy","Mddyyyy","ddMyyyy","Mdyyyy","dMyyyy","yyyy","Mdyy","dMyy","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0){return r;}}catch(e){}
return g._start.call({},s);};$D._parse=$D.parse;$D.parse=function(s){var r=null;if(!s){return null;}
if(s instanceof Date){return s;}
try{r=$D.Grammar.start.call({},s.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1"));}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};$D.getParseFunction=function(fx){var fn=$D.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};};$D.parseExact=function(s,fx){return $D.getParseFunction(fx)(s);};}());
;
jQuery(document).ready(function($){
	// browser window scroll (in pixels) after which the "back to top" link is shown
	var offset = 300,
		//browser window scroll (in pixels) after which the "back to top" link opacity is reduced
		offset_opacity = 1200,
		//duration of the top scrolling animation (in ms)
		scroll_top_duration = 700,
		//grab the "back to top" link
		$back_to_top = $('.backtotop');

	//hide or show the "back to top" link
	$(window).scroll(function(){
		( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
		if( $(this).scrollTop() > offset_opacity ) { 
			$back_to_top.addClass('cd-fade-out');
		}
	});

	//smooth scroll to top
	$back_to_top.on('click', function(event){
		event.preventDefault();
		$('body,html').animate({
			scrollTop: 0 ,
		 	}, scroll_top_duration
		);
	});

    //Volver al menu principal
	$(".backtomenu").click(function (event) {
	    event.preventDefault();
	    $(".MenuPrincipalContainer  a:first").focus();
	    $('html, body').animate({
	        scrollTop: $("#BackToMainMenu").offset().top
	    }, 2000);
	});

});;
!function(i){"use strict";"function"==typeof define&&define.amd?define(["jquery"],i):"undefined"!=typeof exports?module.exports=i(require("jquery")):i(jQuery)}(function(i){"use strict";var e=window.Slick||{};(e=function(){var e=0;return function(t,o){var s,n=this;n.defaults={accessibility:!0,adaptiveHeight:!1,appendArrows:i(t),appendDots:i(t),arrows:!0,asNavFor:null,prevArrow:'<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',nextArrow:'<button class="slick-next" aria-label="Next" type="button">Next</button>',autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",customPaging:function(e,t){return i('<button type="button" />').text(t+1)},dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,focusOnChange:!1,infinite:!0,initialSlide:0,lazyLoad:"ondemand",mobileFirst:!1,pauseOnHover:!0,pauseOnFocus:!0,pauseOnDotsHover:!1,respondTo:"window",responsive:null,rows:1,rtl:!1,slide:"",slidesPerRow:1,slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,useTransform:!0,variableWidth:!1,vertical:!1,verticalSwiping:!1,waitForAnimate:!0,zIndex:1e3},n.initials={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,$dots:null,listWidth:null,listHeight:null,loadIndex:0,$nextArrow:null,$prevArrow:null,scrolling:!1,slideCount:null,slideWidth:null,$slideTrack:null,$slides:null,sliding:!1,slideOffset:0,swipeLeft:null,swiping:!1,$list:null,touchObject:{},transformsEnabled:!1,unslicked:!1},i.extend(n,n.initials),n.activeBreakpoint=null,n.animType=null,n.animProp=null,n.breakpoints=[],n.breakpointSettings=[],n.cssTransitions=!1,n.focussed=!1,n.interrupted=!1,n.hidden="hidden",n.paused=!0,n.positionProp=null,n.respondTo=null,n.rowCount=1,n.shouldClick=!0,n.$slider=i(t),n.$slidesCache=null,n.transformType=null,n.transitionType=null,n.visibilityChange="visibilitychange",n.windowWidth=0,n.windowTimer=null,s=i(t).data("slick")||{},n.options=i.extend({},n.defaults,o,s),n.currentSlide=n.options.initialSlide,n.originalSettings=n.options,void 0!==document.mozHidden?(n.hidden="mozHidden",n.visibilityChange="mozvisibilitychange"):void 0!==document.webkitHidden&&(n.hidden="webkitHidden",n.visibilityChange="webkitvisibilitychange"),n.autoPlay=i.proxy(n.autoPlay,n),n.autoPlayClear=i.proxy(n.autoPlayClear,n),n.autoPlayIterator=i.proxy(n.autoPlayIterator,n),n.changeSlide=i.proxy(n.changeSlide,n),n.clickHandler=i.proxy(n.clickHandler,n),n.selectHandler=i.proxy(n.selectHandler,n),n.setPosition=i.proxy(n.setPosition,n),n.swipeHandler=i.proxy(n.swipeHandler,n),n.dragHandler=i.proxy(n.dragHandler,n),n.keyHandler=i.proxy(n.keyHandler,n),n.instanceUid=e++,n.htmlExpr=/^(?:\s*(<[\w\W]+>)[^>]*)$/,n.registerBreakpoints(),n.init(!0)}}()).prototype.activateADA=function(){this.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})},e.prototype.addSlide=e.prototype.slickAdd=function(e,t,o){var s=this;if("boolean"==typeof t)o=t,t=null;else if(t<0||t>=s.slideCount)return!1;s.unload(),"number"==typeof t?0===t&&0===s.$slides.length?i(e).appendTo(s.$slideTrack):o?i(e).insertBefore(s.$slides.eq(t)):i(e).insertAfter(s.$slides.eq(t)):!0===o?i(e).prependTo(s.$slideTrack):i(e).appendTo(s.$slideTrack),s.$slides=s.$slideTrack.children(this.options.slide),s.$slideTrack.children(this.options.slide).detach(),s.$slideTrack.append(s.$slides),s.$slides.each(function(e,t){i(t).attr("data-slick-index",e)}),s.$slidesCache=s.$slides,s.reinit()},e.prototype.animateHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.animate({height:e},i.options.speed)}},e.prototype.animateSlide=function(e,t){var o={},s=this;s.animateHeight(),!0===s.options.rtl&&!1===s.options.vertical&&(e=-e),!1===s.transformsEnabled?!1===s.options.vertical?s.$slideTrack.animate({left:e},s.options.speed,s.options.easing,t):s.$slideTrack.animate({top:e},s.options.speed,s.options.easing,t):!1===s.cssTransitions?(!0===s.options.rtl&&(s.currentLeft=-s.currentLeft),i({animStart:s.currentLeft}).animate({animStart:e},{duration:s.options.speed,easing:s.options.easing,step:function(i){i=Math.ceil(i),!1===s.options.vertical?(o[s.animType]="translate("+i+"px, 0px)",s.$slideTrack.css(o)):(o[s.animType]="translate(0px,"+i+"px)",s.$slideTrack.css(o))},complete:function(){t&&t.call()}})):(s.applyTransition(),e=Math.ceil(e),!1===s.options.vertical?o[s.animType]="translate3d("+e+"px, 0px, 0px)":o[s.animType]="translate3d(0px,"+e+"px, 0px)",s.$slideTrack.css(o),t&&setTimeout(function(){s.disableTransition(),t.call()},s.options.speed))},e.prototype.getNavTarget=function(){var e=this,t=e.options.asNavFor;return t&&null!==t&&(t=i(t).not(e.$slider)),t},e.prototype.asNavFor=function(e){var t=this.getNavTarget();null!==t&&"object"==typeof t&&t.each(function(){var t=i(this).slick("getSlick");t.unslicked||t.slideHandler(e,!0)})},e.prototype.applyTransition=function(i){var e=this,t={};!1===e.options.fade?t[e.transitionType]=e.transformType+" "+e.options.speed+"ms "+e.options.cssEase:t[e.transitionType]="opacity "+e.options.speed+"ms "+e.options.cssEase,!1===e.options.fade?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.autoPlay=function(){var i=this;i.autoPlayClear(),i.slideCount>i.options.slidesToShow&&(i.autoPlayTimer=setInterval(i.autoPlayIterator,i.options.autoplaySpeed))},e.prototype.autoPlayClear=function(){var i=this;i.autoPlayTimer&&clearInterval(i.autoPlayTimer)},e.prototype.autoPlayIterator=function(){var i=this,e=i.currentSlide+i.options.slidesToScroll;i.paused||i.interrupted||i.focussed||(!1===i.options.infinite&&(1===i.direction&&i.currentSlide+1===i.slideCount-1?i.direction=0:0===i.direction&&(e=i.currentSlide-i.options.slidesToScroll,i.currentSlide-1==0&&(i.direction=1))),i.slideHandler(e))},e.prototype.buildArrows=function(){var e=this;!0===e.options.arrows&&(e.$prevArrow=i(e.options.prevArrow).addClass("slick-arrow"),e.$nextArrow=i(e.options.nextArrow).addClass("slick-arrow"),e.slideCount>e.options.slidesToShow?(e.$prevArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.$nextArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.prependTo(e.options.appendArrows),e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.appendTo(e.options.appendArrows),!0!==e.options.infinite&&e.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true")):e.$prevArrow.add(e.$nextArrow).addClass("slick-hidden").attr({"aria-disabled":"true",tabindex:"-1"}))},e.prototype.buildDots=function(){var e,t,o=this;if(!0===o.options.dots){for(o.$slider.addClass("slick-dotted"),t=i("<ul />").addClass(o.options.dotsClass),e=0;e<=o.getDotCount();e+=1)t.append(i("<li />").append(o.options.customPaging.call(this,o,e)));o.$dots=t.appendTo(o.options.appendDots),o.$dots.find("li").first().addClass("slick-active")}},e.prototype.buildOut=function(){var e=this;e.$slides=e.$slider.children(e.options.slide+":not(.slick-cloned)").addClass("slick-slide"),e.slideCount=e.$slides.length,e.$slides.each(function(e,t){i(t).attr("data-slick-index",e).data("originalStyling",i(t).attr("style")||"")}),e.$slider.addClass("slick-slider"),e.$slideTrack=0===e.slideCount?i('<div class="slick-track"/>').appendTo(e.$slider):e.$slides.wrapAll('<div class="slick-track"/>').parent(),e.$list=e.$slideTrack.wrap('<div class="slick-list"/>').parent(),e.$slideTrack.css("opacity",0),!0!==e.options.centerMode&&!0!==e.options.swipeToSlide||(e.options.slidesToScroll=1),i("img[data-lazy]",e.$slider).not("[src]").addClass("slick-loading"),e.setupInfinite(),e.buildArrows(),e.buildDots(),e.updateDots(),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),!0===e.options.draggable&&e.$list.addClass("draggable")},e.prototype.buildRows=function(){var i,e,t,o,s,n,r,l=this;if(o=document.createDocumentFragment(),n=l.$slider.children(),l.options.rows>1){for(r=l.options.slidesPerRow*l.options.rows,s=Math.ceil(n.length/r),i=0;i<s;i++){var d=document.createElement("div");for(e=0;e<l.options.rows;e++){var a=document.createElement("div");for(t=0;t<l.options.slidesPerRow;t++){var c=i*r+(e*l.options.slidesPerRow+t);n.get(c)&&a.appendChild(n.get(c))}d.appendChild(a)}o.appendChild(d)}l.$slider.empty().append(o),l.$slider.children().children().children().css({width:100/l.options.slidesPerRow+"%",display:"inline-block"})}},e.prototype.checkResponsive=function(e,t){var o,s,n,r=this,l=!1,d=r.$slider.width(),a=window.innerWidth||i(window).width();if("window"===r.respondTo?n=a:"slider"===r.respondTo?n=d:"min"===r.respondTo&&(n=Math.min(a,d)),r.options.responsive&&r.options.responsive.length&&null!==r.options.responsive){s=null;for(o in r.breakpoints)r.breakpoints.hasOwnProperty(o)&&(!1===r.originalSettings.mobileFirst?n<r.breakpoints[o]&&(s=r.breakpoints[o]):n>r.breakpoints[o]&&(s=r.breakpoints[o]));null!==s?null!==r.activeBreakpoint?(s!==r.activeBreakpoint||t)&&(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):null!==r.activeBreakpoint&&(r.activeBreakpoint=null,r.options=r.originalSettings,!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e),l=s),e||!1===l||r.$slider.trigger("breakpoint",[r,l])}},e.prototype.changeSlide=function(e,t){var o,s,n,r=this,l=i(e.currentTarget);switch(l.is("a")&&e.preventDefault(),l.is("li")||(l=l.closest("li")),n=r.slideCount%r.options.slidesToScroll!=0,o=n?0:(r.slideCount-r.currentSlide)%r.options.slidesToScroll,e.data.message){case"previous":s=0===o?r.options.slidesToScroll:r.options.slidesToShow-o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide-s,!1,t);break;case"next":s=0===o?r.options.slidesToScroll:o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide+s,!1,t);break;case"index":var d=0===e.data.index?0:e.data.index||l.index()*r.options.slidesToScroll;r.slideHandler(r.checkNavigable(d),!1,t),l.children().trigger("focus");break;default:return}},e.prototype.checkNavigable=function(i){var e,t;if(e=this.getNavigableIndexes(),t=0,i>e[e.length-1])i=e[e.length-1];else for(var o in e){if(i<e[o]){i=t;break}t=e[o]}return i},e.prototype.cleanUpEvents=function(){var e=this;e.options.dots&&null!==e.$dots&&(i("li",e.$dots).off("click.slick",e.changeSlide).off("mouseenter.slick",i.proxy(e.interrupt,e,!0)).off("mouseleave.slick",i.proxy(e.interrupt,e,!1)),!0===e.options.accessibility&&e.$dots.off("keydown.slick",e.keyHandler)),e.$slider.off("focus.slick blur.slick"),!0===e.options.arrows&&e.slideCount>e.options.slidesToShow&&(e.$prevArrow&&e.$prevArrow.off("click.slick",e.changeSlide),e.$nextArrow&&e.$nextArrow.off("click.slick",e.changeSlide),!0===e.options.accessibility&&(e.$prevArrow&&e.$prevArrow.off("keydown.slick",e.keyHandler),e.$nextArrow&&e.$nextArrow.off("keydown.slick",e.keyHandler))),e.$list.off("touchstart.slick mousedown.slick",e.swipeHandler),e.$list.off("touchmove.slick mousemove.slick",e.swipeHandler),e.$list.off("touchend.slick mouseup.slick",e.swipeHandler),e.$list.off("touchcancel.slick mouseleave.slick",e.swipeHandler),e.$list.off("click.slick",e.clickHandler),i(document).off(e.visibilityChange,e.visibility),e.cleanUpSlideEvents(),!0===e.options.accessibility&&e.$list.off("keydown.slick",e.keyHandler),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().off("click.slick",e.selectHandler),i(window).off("orientationchange.slick.slick-"+e.instanceUid,e.orientationChange),i(window).off("resize.slick.slick-"+e.instanceUid,e.resize),i("[draggable!=true]",e.$slideTrack).off("dragstart",e.preventDefault),i(window).off("load.slick.slick-"+e.instanceUid,e.setPosition)},e.prototype.cleanUpSlideEvents=function(){var e=this;e.$list.off("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.off("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.cleanUpRows=function(){var i,e=this;e.options.rows>1&&((i=e.$slides.children().children()).removeAttr("style"),e.$slider.empty().append(i))},e.prototype.clickHandler=function(i){!1===this.shouldClick&&(i.stopImmediatePropagation(),i.stopPropagation(),i.preventDefault())},e.prototype.destroy=function(e){var t=this;t.autoPlayClear(),t.touchObject={},t.cleanUpEvents(),i(".slick-cloned",t.$slider).detach(),t.$dots&&t.$dots.remove(),t.$prevArrow&&t.$prevArrow.length&&(t.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.prevArrow)&&t.$prevArrow.remove()),t.$nextArrow&&t.$nextArrow.length&&(t.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.nextArrow)&&t.$nextArrow.remove()),t.$slides&&(t.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){i(this).attr("style",i(this).data("originalStyling"))}),t.$slideTrack.children(this.options.slide).detach(),t.$slideTrack.detach(),t.$list.detach(),t.$slider.append(t.$slides)),t.cleanUpRows(),t.$slider.removeClass("slick-slider"),t.$slider.removeClass("slick-initialized"),t.$slider.removeClass("slick-dotted"),t.unslicked=!0,e||t.$slider.trigger("destroy",[t])},e.prototype.disableTransition=function(i){var e=this,t={};t[e.transitionType]="",!1===e.options.fade?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.fadeSlide=function(i,e){var t=this;!1===t.cssTransitions?(t.$slides.eq(i).css({zIndex:t.options.zIndex}),t.$slides.eq(i).animate({opacity:1},t.options.speed,t.options.easing,e)):(t.applyTransition(i),t.$slides.eq(i).css({opacity:1,zIndex:t.options.zIndex}),e&&setTimeout(function(){t.disableTransition(i),e.call()},t.options.speed))},e.prototype.fadeSlideOut=function(i){var e=this;!1===e.cssTransitions?e.$slides.eq(i).animate({opacity:0,zIndex:e.options.zIndex-2},e.options.speed,e.options.easing):(e.applyTransition(i),e.$slides.eq(i).css({opacity:0,zIndex:e.options.zIndex-2}))},e.prototype.filterSlides=e.prototype.slickFilter=function(i){var e=this;null!==i&&(e.$slidesCache=e.$slides,e.unload(),e.$slideTrack.children(this.options.slide).detach(),e.$slidesCache.filter(i).appendTo(e.$slideTrack),e.reinit())},e.prototype.focusHandler=function(){var e=this;e.$slider.off("focus.slick blur.slick").on("focus.slick blur.slick","*",function(t){t.stopImmediatePropagation();var o=i(this);setTimeout(function(){e.options.pauseOnFocus&&(e.focussed=o.is(":focus"),e.autoPlay())},0)})},e.prototype.getCurrent=e.prototype.slickCurrentSlide=function(){return this.currentSlide},e.prototype.getDotCount=function(){var i=this,e=0,t=0,o=0;if(!0===i.options.infinite)if(i.slideCount<=i.options.slidesToShow)++o;else for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else if(!0===i.options.centerMode)o=i.slideCount;else if(i.options.asNavFor)for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else o=1+Math.ceil((i.slideCount-i.options.slidesToShow)/i.options.slidesToScroll);return o-1},e.prototype.getLeft=function(i){var e,t,o,s,n=this,r=0;return n.slideOffset=0,t=n.$slides.first().outerHeight(!0),!0===n.options.infinite?(n.slideCount>n.options.slidesToShow&&(n.slideOffset=n.slideWidth*n.options.slidesToShow*-1,s=-1,!0===n.options.vertical&&!0===n.options.centerMode&&(2===n.options.slidesToShow?s=-1.5:1===n.options.slidesToShow&&(s=-2)),r=t*n.options.slidesToShow*s),n.slideCount%n.options.slidesToScroll!=0&&i+n.options.slidesToScroll>n.slideCount&&n.slideCount>n.options.slidesToShow&&(i>n.slideCount?(n.slideOffset=(n.options.slidesToShow-(i-n.slideCount))*n.slideWidth*-1,r=(n.options.slidesToShow-(i-n.slideCount))*t*-1):(n.slideOffset=n.slideCount%n.options.slidesToScroll*n.slideWidth*-1,r=n.slideCount%n.options.slidesToScroll*t*-1))):i+n.options.slidesToShow>n.slideCount&&(n.slideOffset=(i+n.options.slidesToShow-n.slideCount)*n.slideWidth,r=(i+n.options.slidesToShow-n.slideCount)*t),n.slideCount<=n.options.slidesToShow&&(n.slideOffset=0,r=0),!0===n.options.centerMode&&n.slideCount<=n.options.slidesToShow?n.slideOffset=n.slideWidth*Math.floor(n.options.slidesToShow)/2-n.slideWidth*n.slideCount/2:!0===n.options.centerMode&&!0===n.options.infinite?n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)-n.slideWidth:!0===n.options.centerMode&&(n.slideOffset=0,n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)),e=!1===n.options.vertical?i*n.slideWidth*-1+n.slideOffset:i*t*-1+r,!0===n.options.variableWidth&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,!0===n.options.centerMode&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow+1),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,e+=(n.$list.width()-o.outerWidth())/2)),e},e.prototype.getOption=e.prototype.slickGetOption=function(i){return this.options[i]},e.prototype.getNavigableIndexes=function(){var i,e=this,t=0,o=0,s=[];for(!1===e.options.infinite?i=e.slideCount:(t=-1*e.options.slidesToScroll,o=-1*e.options.slidesToScroll,i=2*e.slideCount);t<i;)s.push(t),t=o+e.options.slidesToScroll,o+=e.options.slidesToScroll<=e.options.slidesToShow?e.options.slidesToScroll:e.options.slidesToShow;return s},e.prototype.getSlick=function(){return this},e.prototype.getSlideCount=function(){var e,t,o=this;return t=!0===o.options.centerMode?o.slideWidth*Math.floor(o.options.slidesToShow/2):0,!0===o.options.swipeToSlide?(o.$slideTrack.find(".slick-slide").each(function(s,n){if(n.offsetLeft-t+i(n).outerWidth()/2>-1*o.swipeLeft)return e=n,!1}),Math.abs(i(e).attr("data-slick-index")-o.currentSlide)||1):o.options.slidesToScroll},e.prototype.goTo=e.prototype.slickGoTo=function(i,e){this.changeSlide({data:{message:"index",index:parseInt(i)}},e)},e.prototype.init=function(e){var t=this;i(t.$slider).hasClass("slick-initialized")||(i(t.$slider).addClass("slick-initialized"),t.buildRows(),t.buildOut(),t.setProps(),t.startLoad(),t.loadSlider(),t.initializeEvents(),t.updateArrows(),t.updateDots(),t.checkResponsive(!0),t.focusHandler()),e&&t.$slider.trigger("init",[t]),!0===t.options.accessibility&&t.initADA(),t.options.autoplay&&(t.paused=!1,t.autoPlay())},e.prototype.initADA=function(){var e=this,t=Math.ceil(e.slideCount/e.options.slidesToShow),o=e.getNavigableIndexes().filter(function(i){return i>=0&&i<e.slideCount});e.$slides.add(e.$slideTrack.find(".slick-cloned")).attr({"aria-hidden":"true",tabindex:"-1"}).find("a, input, button, select").attr({tabindex:"-1"}),null!==e.$dots&&(e.$slides.not(e.$slideTrack.find(".slick-cloned")).each(function(t){var s=o.indexOf(t);i(this).attr({role:"tabpanel",id:"slick-slide"+e.instanceUid+t,tabindex:-1}),-1!==s&&i(this).attr({"aria-describedby":"slick-slide-control"+e.instanceUid+s})}),e.$dots.attr("role","tablist").find("li").each(function(s){var n=o[s];i(this).attr({role:"presentation"}),i(this).find("button").first().attr({role:"tab",id:"slick-slide-control"+e.instanceUid+s,"aria-controls":"slick-slide"+e.instanceUid+n,"aria-label":s+1+" of "+t,"aria-selected":null,tabindex:"-1"})}).eq(e.currentSlide).find("button").attr({"aria-selected":"true",tabindex:"0"}).end());for(var s=e.currentSlide,n=s+e.options.slidesToShow;s<n;s++)e.$slides.eq(s).attr("tabindex",0);e.activateADA()},e.prototype.initArrowEvents=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.off("click.slick").on("click.slick",{message:"previous"},i.changeSlide),i.$nextArrow.off("click.slick").on("click.slick",{message:"next"},i.changeSlide),!0===i.options.accessibility&&(i.$prevArrow.on("keydown.slick",i.keyHandler),i.$nextArrow.on("keydown.slick",i.keyHandler)))},e.prototype.initDotEvents=function(){var e=this;!0===e.options.dots&&(i("li",e.$dots).on("click.slick",{message:"index"},e.changeSlide),!0===e.options.accessibility&&e.$dots.on("keydown.slick",e.keyHandler)),!0===e.options.dots&&!0===e.options.pauseOnDotsHover&&i("li",e.$dots).on("mouseenter.slick",i.proxy(e.interrupt,e,!0)).on("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.initSlideEvents=function(){var e=this;e.options.pauseOnHover&&(e.$list.on("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.on("mouseleave.slick",i.proxy(e.interrupt,e,!1)))},e.prototype.initializeEvents=function(){var e=this;e.initArrowEvents(),e.initDotEvents(),e.initSlideEvents(),e.$list.on("touchstart.slick mousedown.slick",{action:"start"},e.swipeHandler),e.$list.on("touchmove.slick mousemove.slick",{action:"move"},e.swipeHandler),e.$list.on("touchend.slick mouseup.slick",{action:"end"},e.swipeHandler),e.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},e.swipeHandler),e.$list.on("click.slick",e.clickHandler),i(document).on(e.visibilityChange,i.proxy(e.visibility,e)),!0===e.options.accessibility&&e.$list.on("keydown.slick",e.keyHandler),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),i(window).on("orientationchange.slick.slick-"+e.instanceUid,i.proxy(e.orientationChange,e)),i(window).on("resize.slick.slick-"+e.instanceUid,i.proxy(e.resize,e)),i("[draggable!=true]",e.$slideTrack).on("dragstart",e.preventDefault),i(window).on("load.slick.slick-"+e.instanceUid,e.setPosition),i(e.setPosition)},e.prototype.initUI=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.show(),i.$nextArrow.show()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.show()},e.prototype.keyHandler=function(i){var e=this;i.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===i.keyCode&&!0===e.options.accessibility?e.changeSlide({data:{message:!0===e.options.rtl?"next":"previous"}}):39===i.keyCode&&!0===e.options.accessibility&&e.changeSlide({data:{message:!0===e.options.rtl?"previous":"next"}}))},e.prototype.lazyLoad=function(){function e(e){i("img[data-lazy]",e).each(function(){var e=i(this),t=i(this).attr("data-lazy"),o=i(this).attr("data-srcset"),s=i(this).attr("data-sizes")||n.$slider.attr("data-sizes"),r=document.createElement("img");r.onload=function(){e.animate({opacity:0},100,function(){o&&(e.attr("srcset",o),s&&e.attr("sizes",s)),e.attr("src",t).animate({opacity:1},200,function(){e.removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading")}),n.$slider.trigger("lazyLoaded",[n,e,t])})},r.onerror=function(){e.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),n.$slider.trigger("lazyLoadError",[n,e,t])},r.src=t})}var t,o,s,n=this;if(!0===n.options.centerMode?!0===n.options.infinite?s=(o=n.currentSlide+(n.options.slidesToShow/2+1))+n.options.slidesToShow+2:(o=Math.max(0,n.currentSlide-(n.options.slidesToShow/2+1)),s=n.options.slidesToShow/2+1+2+n.currentSlide):(o=n.options.infinite?n.options.slidesToShow+n.currentSlide:n.currentSlide,s=Math.ceil(o+n.options.slidesToShow),!0===n.options.fade&&(o>0&&o--,s<=n.slideCount&&s++)),t=n.$slider.find(".slick-slide").slice(o,s),"anticipated"===n.options.lazyLoad)for(var r=o-1,l=s,d=n.$slider.find(".slick-slide"),a=0;a<n.options.slidesToScroll;a++)r<0&&(r=n.slideCount-1),t=(t=t.add(d.eq(r))).add(d.eq(l)),r--,l++;e(t),n.slideCount<=n.options.slidesToShow?e(n.$slider.find(".slick-slide")):n.currentSlide>=n.slideCount-n.options.slidesToShow?e(n.$slider.find(".slick-cloned").slice(0,n.options.slidesToShow)):0===n.currentSlide&&e(n.$slider.find(".slick-cloned").slice(-1*n.options.slidesToShow))},e.prototype.loadSlider=function(){var i=this;i.setPosition(),i.$slideTrack.css({opacity:1}),i.$slider.removeClass("slick-loading"),i.initUI(),"progressive"===i.options.lazyLoad&&i.progressiveLazyLoad()},e.prototype.next=e.prototype.slickNext=function(){this.changeSlide({data:{message:"next"}})},e.prototype.orientationChange=function(){var i=this;i.checkResponsive(),i.setPosition()},e.prototype.pause=e.prototype.slickPause=function(){var i=this;i.autoPlayClear(),i.paused=!0},e.prototype.play=e.prototype.slickPlay=function(){var i=this;i.autoPlay(),i.options.autoplay=!0,i.paused=!1,i.focussed=!1,i.interrupted=!1},e.prototype.postSlide=function(e){var t=this;t.unslicked||(t.$slider.trigger("afterChange",[t,e]),t.animating=!1,t.slideCount>t.options.slidesToShow&&t.setPosition(),t.swipeLeft=null,t.options.autoplay&&t.autoPlay(),!0===t.options.accessibility&&(t.initADA(),t.options.focusOnChange&&i(t.$slides.get(t.currentSlide)).attr("tabindex",0).focus()))},e.prototype.prev=e.prototype.slickPrev=function(){this.changeSlide({data:{message:"previous"}})},e.prototype.preventDefault=function(i){i.preventDefault()},e.prototype.progressiveLazyLoad=function(e){e=e||1;var t,o,s,n,r,l=this,d=i("img[data-lazy]",l.$slider);d.length?(t=d.first(),o=t.attr("data-lazy"),s=t.attr("data-srcset"),n=t.attr("data-sizes")||l.$slider.attr("data-sizes"),(r=document.createElement("img")).onload=function(){s&&(t.attr("srcset",s),n&&t.attr("sizes",n)),t.attr("src",o).removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading"),!0===l.options.adaptiveHeight&&l.setPosition(),l.$slider.trigger("lazyLoaded",[l,t,o]),l.progressiveLazyLoad()},r.onerror=function(){e<3?setTimeout(function(){l.progressiveLazyLoad(e+1)},500):(t.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),l.$slider.trigger("lazyLoadError",[l,t,o]),l.progressiveLazyLoad())},r.src=o):l.$slider.trigger("allImagesLoaded",[l])},e.prototype.refresh=function(e){var t,o,s=this;o=s.slideCount-s.options.slidesToShow,!s.options.infinite&&s.currentSlide>o&&(s.currentSlide=o),s.slideCount<=s.options.slidesToShow&&(s.currentSlide=0),t=s.currentSlide,s.destroy(!0),i.extend(s,s.initials,{currentSlide:t}),s.init(),e||s.changeSlide({data:{message:"index",index:t}},!1)},e.prototype.registerBreakpoints=function(){var e,t,o,s=this,n=s.options.responsive||null;if("array"===i.type(n)&&n.length){s.respondTo=s.options.respondTo||"window";for(e in n)if(o=s.breakpoints.length-1,n.hasOwnProperty(e)){for(t=n[e].breakpoint;o>=0;)s.breakpoints[o]&&s.breakpoints[o]===t&&s.breakpoints.splice(o,1),o--;s.breakpoints.push(t),s.breakpointSettings[t]=n[e].settings}s.breakpoints.sort(function(i,e){return s.options.mobileFirst?i-e:e-i})}},e.prototype.reinit=function(){var e=this;e.$slides=e.$slideTrack.children(e.options.slide).addClass("slick-slide"),e.slideCount=e.$slides.length,e.currentSlide>=e.slideCount&&0!==e.currentSlide&&(e.currentSlide=e.currentSlide-e.options.slidesToScroll),e.slideCount<=e.options.slidesToShow&&(e.currentSlide=0),e.registerBreakpoints(),e.setProps(),e.setupInfinite(),e.buildArrows(),e.updateArrows(),e.initArrowEvents(),e.buildDots(),e.updateDots(),e.initDotEvents(),e.cleanUpSlideEvents(),e.initSlideEvents(),e.checkResponsive(!1,!0),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),e.setPosition(),e.focusHandler(),e.paused=!e.options.autoplay,e.autoPlay(),e.$slider.trigger("reInit",[e])},e.prototype.resize=function(){var e=this;i(window).width()!==e.windowWidth&&(clearTimeout(e.windowDelay),e.windowDelay=window.setTimeout(function(){e.windowWidth=i(window).width(),e.checkResponsive(),e.unslicked||e.setPosition()},50))},e.prototype.removeSlide=e.prototype.slickRemove=function(i,e,t){var o=this;if(i="boolean"==typeof i?!0===(e=i)?0:o.slideCount-1:!0===e?--i:i,o.slideCount<1||i<0||i>o.slideCount-1)return!1;o.unload(),!0===t?o.$slideTrack.children().remove():o.$slideTrack.children(this.options.slide).eq(i).remove(),o.$slides=o.$slideTrack.children(this.options.slide),o.$slideTrack.children(this.options.slide).detach(),o.$slideTrack.append(o.$slides),o.$slidesCache=o.$slides,o.reinit()},e.prototype.setCSS=function(i){var e,t,o=this,s={};!0===o.options.rtl&&(i=-i),e="left"==o.positionProp?Math.ceil(i)+"px":"0px",t="top"==o.positionProp?Math.ceil(i)+"px":"0px",s[o.positionProp]=i,!1===o.transformsEnabled?o.$slideTrack.css(s):(s={},!1===o.cssTransitions?(s[o.animType]="translate("+e+", "+t+")",o.$slideTrack.css(s)):(s[o.animType]="translate3d("+e+", "+t+", 0px)",o.$slideTrack.css(s)))},e.prototype.setDimensions=function(){var i=this;!1===i.options.vertical?!0===i.options.centerMode&&i.$list.css({padding:"0px "+i.options.centerPadding}):(i.$list.height(i.$slides.first().outerHeight(!0)*i.options.slidesToShow),!0===i.options.centerMode&&i.$list.css({padding:i.options.centerPadding+" 0px"})),i.listWidth=i.$list.width(),i.listHeight=i.$list.height(),!1===i.options.vertical&&!1===i.options.variableWidth?(i.slideWidth=Math.ceil(i.listWidth/i.options.slidesToShow),i.$slideTrack.width(Math.ceil(i.slideWidth*i.$slideTrack.children(".slick-slide").length))):!0===i.options.variableWidth?i.$slideTrack.width(5e3*i.slideCount):(i.slideWidth=Math.ceil(i.listWidth),i.$slideTrack.height(Math.ceil(i.$slides.first().outerHeight(!0)*i.$slideTrack.children(".slick-slide").length)));var e=i.$slides.first().outerWidth(!0)-i.$slides.first().width();!1===i.options.variableWidth&&i.$slideTrack.children(".slick-slide").width(i.slideWidth-e)},e.prototype.setFade=function(){var e,t=this;t.$slides.each(function(o,s){e=t.slideWidth*o*-1,!0===t.options.rtl?i(s).css({position:"relative",right:e,top:0,zIndex:t.options.zIndex-2,opacity:0}):i(s).css({position:"relative",left:e,top:0,zIndex:t.options.zIndex-2,opacity:0})}),t.$slides.eq(t.currentSlide).css({zIndex:t.options.zIndex-1,opacity:1})},e.prototype.setHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.css("height",e)}},e.prototype.setOption=e.prototype.slickSetOption=function(){var e,t,o,s,n,r=this,l=!1;if("object"===i.type(arguments[0])?(o=arguments[0],l=arguments[1],n="multiple"):"string"===i.type(arguments[0])&&(o=arguments[0],s=arguments[1],l=arguments[2],"responsive"===arguments[0]&&"array"===i.type(arguments[1])?n="responsive":void 0!==arguments[1]&&(n="single")),"single"===n)r.options[o]=s;else if("multiple"===n)i.each(o,function(i,e){r.options[i]=e});else if("responsive"===n)for(t in s)if("array"!==i.type(r.options.responsive))r.options.responsive=[s[t]];else{for(e=r.options.responsive.length-1;e>=0;)r.options.responsive[e].breakpoint===s[t].breakpoint&&r.options.responsive.splice(e,1),e--;r.options.responsive.push(s[t])}l&&(r.unload(),r.reinit())},e.prototype.setPosition=function(){var i=this;i.setDimensions(),i.setHeight(),!1===i.options.fade?i.setCSS(i.getLeft(i.currentSlide)):i.setFade(),i.$slider.trigger("setPosition",[i])},e.prototype.setProps=function(){var i=this,e=document.body.style;i.positionProp=!0===i.options.vertical?"top":"left","top"===i.positionProp?i.$slider.addClass("slick-vertical"):i.$slider.removeClass("slick-vertical"),void 0===e.WebkitTransition&&void 0===e.MozTransition&&void 0===e.msTransition||!0===i.options.useCSS&&(i.cssTransitions=!0),i.options.fade&&("number"==typeof i.options.zIndex?i.options.zIndex<3&&(i.options.zIndex=3):i.options.zIndex=i.defaults.zIndex),void 0!==e.OTransform&&(i.animType="OTransform",i.transformType="-o-transform",i.transitionType="OTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.MozTransform&&(i.animType="MozTransform",i.transformType="-moz-transform",i.transitionType="MozTransition",void 0===e.perspectiveProperty&&void 0===e.MozPerspective&&(i.animType=!1)),void 0!==e.webkitTransform&&(i.animType="webkitTransform",i.transformType="-webkit-transform",i.transitionType="webkitTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.msTransform&&(i.animType="msTransform",i.transformType="-ms-transform",i.transitionType="msTransition",void 0===e.msTransform&&(i.animType=!1)),void 0!==e.transform&&!1!==i.animType&&(i.animType="transform",i.transformType="transform",i.transitionType="transition"),i.transformsEnabled=i.options.useTransform&&null!==i.animType&&!1!==i.animType},e.prototype.setSlideClasses=function(i){var e,t,o,s,n=this;if(t=n.$slider.find(".slick-slide").removeClass("slick-active slick-center slick-current").attr("aria-hidden","true"),n.$slides.eq(i).addClass("slick-current"),!0===n.options.centerMode){var r=n.options.slidesToShow%2==0?1:0;e=Math.floor(n.options.slidesToShow/2),!0===n.options.infinite&&(i>=e&&i<=n.slideCount-1-e?n.$slides.slice(i-e+r,i+e+1).addClass("slick-active").attr("aria-hidden","false"):(o=n.options.slidesToShow+i,t.slice(o-e+1+r,o+e+2).addClass("slick-active").attr("aria-hidden","false")),0===i?t.eq(t.length-1-n.options.slidesToShow).addClass("slick-center"):i===n.slideCount-1&&t.eq(n.options.slidesToShow).addClass("slick-center")),n.$slides.eq(i).addClass("slick-center")}else i>=0&&i<=n.slideCount-n.options.slidesToShow?n.$slides.slice(i,i+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"):t.length<=n.options.slidesToShow?t.addClass("slick-active").attr("aria-hidden","false"):(s=n.slideCount%n.options.slidesToShow,o=!0===n.options.infinite?n.options.slidesToShow+i:i,n.options.slidesToShow==n.options.slidesToScroll&&n.slideCount-i<n.options.slidesToShow?t.slice(o-(n.options.slidesToShow-s),o+s).addClass("slick-active").attr("aria-hidden","false"):t.slice(o,o+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"));"ondemand"!==n.options.lazyLoad&&"anticipated"!==n.options.lazyLoad||n.lazyLoad()},e.prototype.setupInfinite=function(){var e,t,o,s=this;if(!0===s.options.fade&&(s.options.centerMode=!1),!0===s.options.infinite&&!1===s.options.fade&&(t=null,s.slideCount>s.options.slidesToShow)){for(o=!0===s.options.centerMode?s.options.slidesToShow+1:s.options.slidesToShow,e=s.slideCount;e>s.slideCount-o;e-=1)t=e-1,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t-s.slideCount).prependTo(s.$slideTrack).addClass("slick-cloned");for(e=0;e<o+s.slideCount;e+=1)t=e,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t+s.slideCount).appendTo(s.$slideTrack).addClass("slick-cloned");s.$slideTrack.find(".slick-cloned").find("[id]").each(function(){i(this).attr("id","")})}},e.prototype.interrupt=function(i){var e=this;i||e.autoPlay(),e.interrupted=i},e.prototype.selectHandler=function(e){var t=this,o=i(e.target).is(".slick-slide")?i(e.target):i(e.target).parents(".slick-slide"),s=parseInt(o.attr("data-slick-index"));s||(s=0),t.slideCount<=t.options.slidesToShow?t.slideHandler(s,!1,!0):t.slideHandler(s)},e.prototype.slideHandler=function(i,e,t){var o,s,n,r,l,d=null,a=this;if(e=e||!1,!(!0===a.animating&&!0===a.options.waitForAnimate||!0===a.options.fade&&a.currentSlide===i))if(!1===e&&a.asNavFor(i),o=i,d=a.getLeft(o),r=a.getLeft(a.currentSlide),a.currentLeft=null===a.swipeLeft?r:a.swipeLeft,!1===a.options.infinite&&!1===a.options.centerMode&&(i<0||i>a.getDotCount()*a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else if(!1===a.options.infinite&&!0===a.options.centerMode&&(i<0||i>a.slideCount-a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else{if(a.options.autoplay&&clearInterval(a.autoPlayTimer),s=o<0?a.slideCount%a.options.slidesToScroll!=0?a.slideCount-a.slideCount%a.options.slidesToScroll:a.slideCount+o:o>=a.slideCount?a.slideCount%a.options.slidesToScroll!=0?0:o-a.slideCount:o,a.animating=!0,a.$slider.trigger("beforeChange",[a,a.currentSlide,s]),n=a.currentSlide,a.currentSlide=s,a.setSlideClasses(a.currentSlide),a.options.asNavFor&&(l=(l=a.getNavTarget()).slick("getSlick")).slideCount<=l.options.slidesToShow&&l.setSlideClasses(a.currentSlide),a.updateDots(),a.updateArrows(),!0===a.options.fade)return!0!==t?(a.fadeSlideOut(n),a.fadeSlide(s,function(){a.postSlide(s)})):a.postSlide(s),void a.animateHeight();!0!==t?a.animateSlide(d,function(){a.postSlide(s)}):a.postSlide(s)}},e.prototype.startLoad=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.hide(),i.$nextArrow.hide()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.hide(),i.$slider.addClass("slick-loading")},e.prototype.swipeDirection=function(){var i,e,t,o,s=this;return i=s.touchObject.startX-s.touchObject.curX,e=s.touchObject.startY-s.touchObject.curY,t=Math.atan2(e,i),(o=Math.round(180*t/Math.PI))<0&&(o=360-Math.abs(o)),o<=45&&o>=0?!1===s.options.rtl?"left":"right":o<=360&&o>=315?!1===s.options.rtl?"left":"right":o>=135&&o<=225?!1===s.options.rtl?"right":"left":!0===s.options.verticalSwiping?o>=35&&o<=135?"down":"up":"vertical"},e.prototype.swipeEnd=function(i){var e,t,o=this;if(o.dragging=!1,o.swiping=!1,o.scrolling)return o.scrolling=!1,!1;if(o.interrupted=!1,o.shouldClick=!(o.touchObject.swipeLength>10),void 0===o.touchObject.curX)return!1;if(!0===o.touchObject.edgeHit&&o.$slider.trigger("edge",[o,o.swipeDirection()]),o.touchObject.swipeLength>=o.touchObject.minSwipe){switch(t=o.swipeDirection()){case"left":case"down":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide+o.getSlideCount()):o.currentSlide+o.getSlideCount(),o.currentDirection=0;break;case"right":case"up":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide-o.getSlideCount()):o.currentSlide-o.getSlideCount(),o.currentDirection=1}"vertical"!=t&&(o.slideHandler(e),o.touchObject={},o.$slider.trigger("swipe",[o,t]))}else o.touchObject.startX!==o.touchObject.curX&&(o.slideHandler(o.currentSlide),o.touchObject={})},e.prototype.swipeHandler=function(i){var e=this;if(!(!1===e.options.swipe||"ontouchend"in document&&!1===e.options.swipe||!1===e.options.draggable&&-1!==i.type.indexOf("mouse")))switch(e.touchObject.fingerCount=i.originalEvent&&void 0!==i.originalEvent.touches?i.originalEvent.touches.length:1,e.touchObject.minSwipe=e.listWidth/e.options.touchThreshold,!0===e.options.verticalSwiping&&(e.touchObject.minSwipe=e.listHeight/e.options.touchThreshold),i.data.action){case"start":e.swipeStart(i);break;case"move":e.swipeMove(i);break;case"end":e.swipeEnd(i)}},e.prototype.swipeMove=function(i){var e,t,o,s,n,r,l=this;return n=void 0!==i.originalEvent?i.originalEvent.touches:null,!(!l.dragging||l.scrolling||n&&1!==n.length)&&(e=l.getLeft(l.currentSlide),l.touchObject.curX=void 0!==n?n[0].pageX:i.clientX,l.touchObject.curY=void 0!==n?n[0].pageY:i.clientY,l.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(l.touchObject.curX-l.touchObject.startX,2))),r=Math.round(Math.sqrt(Math.pow(l.touchObject.curY-l.touchObject.startY,2))),!l.options.verticalSwiping&&!l.swiping&&r>4?(l.scrolling=!0,!1):(!0===l.options.verticalSwiping&&(l.touchObject.swipeLength=r),t=l.swipeDirection(),void 0!==i.originalEvent&&l.touchObject.swipeLength>4&&(l.swiping=!0,i.preventDefault()),s=(!1===l.options.rtl?1:-1)*(l.touchObject.curX>l.touchObject.startX?1:-1),!0===l.options.verticalSwiping&&(s=l.touchObject.curY>l.touchObject.startY?1:-1),o=l.touchObject.swipeLength,l.touchObject.edgeHit=!1,!1===l.options.infinite&&(0===l.currentSlide&&"right"===t||l.currentSlide>=l.getDotCount()&&"left"===t)&&(o=l.touchObject.swipeLength*l.options.edgeFriction,l.touchObject.edgeHit=!0),!1===l.options.vertical?l.swipeLeft=e+o*s:l.swipeLeft=e+o*(l.$list.height()/l.listWidth)*s,!0===l.options.verticalSwiping&&(l.swipeLeft=e+o*s),!0!==l.options.fade&&!1!==l.options.touchMove&&(!0===l.animating?(l.swipeLeft=null,!1):void l.setCSS(l.swipeLeft))))},e.prototype.swipeStart=function(i){var e,t=this;if(t.interrupted=!0,1!==t.touchObject.fingerCount||t.slideCount<=t.options.slidesToShow)return t.touchObject={},!1;void 0!==i.originalEvent&&void 0!==i.originalEvent.touches&&(e=i.originalEvent.touches[0]),t.touchObject.startX=t.touchObject.curX=void 0!==e?e.pageX:i.clientX,t.touchObject.startY=t.touchObject.curY=void 0!==e?e.pageY:i.clientY,t.dragging=!0},e.prototype.unfilterSlides=e.prototype.slickUnfilter=function(){var i=this;null!==i.$slidesCache&&(i.unload(),i.$slideTrack.children(this.options.slide).detach(),i.$slidesCache.appendTo(i.$slideTrack),i.reinit())},e.prototype.unload=function(){var e=this;i(".slick-cloned",e.$slider).remove(),e.$dots&&e.$dots.remove(),e.$prevArrow&&e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.remove(),e.$nextArrow&&e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.remove(),e.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")},e.prototype.unslick=function(i){var e=this;e.$slider.trigger("unslick",[e,i]),e.destroy()},e.prototype.updateArrows=function(){var i=this;Math.floor(i.options.slidesToShow/2),!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&!i.options.infinite&&(i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false"),0===i.currentSlide?(i.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-i.options.slidesToShow&&!1===i.options.centerMode?(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-1&&!0===i.options.centerMode&&(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")))},e.prototype.updateDots=function(){var i=this;null!==i.$dots&&(i.$dots.find("li").removeClass("slick-active").end(),i.$dots.find("li").eq(Math.floor(i.currentSlide/i.options.slidesToScroll)).addClass("slick-active"))},e.prototype.visibility=function(){var i=this;i.options.autoplay&&(document[i.hidden]?i.interrupted=!0:i.interrupted=!1)},i.fn.slick=function(){var i,t,o=this,s=arguments[0],n=Array.prototype.slice.call(arguments,1),r=o.length;for(i=0;i<r;i++)if("object"==typeof s||void 0===s?o[i].slick=new e(o[i],s):t=o[i].slick[s].apply(o[i].slick,n),void 0!==t)return t;return o}});
;
var SetupGoogleAnalytics = function (gtagCode) {
    include("https://www.googletagmanager.com/gtag/js?id="+gtagCode,
    {   dom:true,
        type:"js",
        callback:function(){
            window.dataLayer = window.dataLayer || [];
			
            function gtag(){
				dataLayer.push(arguments);
			}
            
			gtag('js', new Date());
            gtag('config',gtagCode);  
	
		    if (window.categoriasJson !== undefined)
		    {
				gtag('set', 'metric1',    categoriasJson["idpagina"] );
				gtag('set', 'dimension1', categoriasJson["Tipo de documento"] ? categoriasJson["Tipo de documento"] : "-sin tipo de documento-");
				gtag('set', 'dimension2', categoriasJson["Tematica"] ? categoriasJson["Tematica"] : "-sin tema-");
				gtag('set', 'dimension3', categoriasJson["seccion"] ? categoriasJson["seccion"] : "-sin seccion-");
				gtag('set', 'dimension4', categoriasJson["uid"] ? categoriasJson["uid"] : "-desconocido-");
				gtag('set', 'dimension5', categoriasJson["sid"] ? categoriasJson["sid"] : "-sin sid-");
		    }			
        }
    });
};
/*
 *
 *   Basado en revisiones usado SortSite web
 *   * https://hermes-soft.atlassian.net/browse/SGCT-61

* - nav con role link innecesario
* - optionGroup para listas de mas de 10 items
* - role y tabindex para tags A que no lo tenga

 *
 */

function CrearOptionsGroupAccesibilidad($select)  {

    var options = $select.find('option');

    // Agrupar opciones por la misma letra inicial
    var groupedOptions = {};

    options.each(function () {
        var text = $(this).text();
        var initial = text.charAt(0).toUpperCase();

        if (!groupedOptions[initial]) {
            groupedOptions[initial] = [];
        }

        groupedOptions[initial].push(this);
    });

    // Limpiar el <select>
    $select.empty();

    // Crear optgroups y agregar las opciones
    $.each(groupedOptions, function (initial, options) {
        var $optgroup = $('<optgroup>').attr('label', initial);
        $(options).appendTo($optgroup);
        $select.append($optgroup);
    });
}

function FixLinksRepetidosSlickVerMas() {
	
	// ARIA evitar links con href repetidos, When adjacent links go to the same location
	  // Objeto para rastrear los href ya vistos
	  var seenLinks = {};
	  
	  debugger;


  var listaDuplicados = $('a[href].SlickVerMas');
  
  //alert("listaDuplicados:" + listaDuplicados.length);

 // Paso 1: Identificar y modificar enlaces duplicados (de noticias de HAS)
  listaDuplicados.each(function() {
    var $link = $(this);
    var href = $link.attr('href');

    if (true || seenLinks.hasOwnProperty(href)) {
      // Eliminar href y guardar en data-urlrepetido
      $link.removeAttr('href')
           .attr('data-urlrepetido', href)
           .css('cursor', 'pointer') // Opcional: Cambiar cursor
           .addClass('link-repetido'); // Clase para estilos (opcional)
    } else {
      seenLinks[href] = true;
    }
  });

  // Paso 2: Listener para enlaces con data-urlrepetido
  $(document).on('click', 'a[data-urlrepetido]', function(e) {
    e.preventDefault();
    var url = $(this).data('urlrepetido');
    window.location.href = url; // Redirigir
  });
	  
	  
}


//NO USADO, no es necesario ni debido
function FixLinksSinTabIndex() 
{
	debugger;
	
		var maxTabIndex = GetMaxTabIndex();
		if (maxTabIndex >= 0) {
			//lista = $('a:not([href]):not([tabIndex])');
			lista = $('a:not([tabIndex])');

			lista.each(function () {
				maxTabIndex++;
				$(this).attr('tabIndex', maxTabIndex);
			});
		}
}

//NO USADO, no es necesario ni debido
function FixTabIndexEnCeroOMenor()
{
	var lista = $('a[tabIndex]');
	
	debugger;	
	
	var maxTabIndex = GetMaxTabIndex();
	var fin = lista.length;
    if (maxTabIndex >= 0)
	{
		for	(var i = 0; i < fin; i++)
		{
			if (lista[i].tabIndex <= 0)
			{
				maxTabIndex++;
				lista[i].tabIndex = maxTabIndex;
			}
		}
	}
}

function GetMaxTabIndex()
{
	// Obtener todos los elementos <a> con el atributo tabIndex
	const $linksWithTabIndex = $('a[tabindex]');

	// Inicializar la variable para el valor máximo
	let maxTabIndex = 0;

	// Recorrer cada elemento y comparar su tabIndex
	$linksWithTabIndex.each(function() {
		const currentTabIndex = parseInt($(this).attr('tabindex'), 10);
		if (!isNaN(currentTabIndex)) {
			maxTabIndex = Math.max(maxTabIndex, currentTabIndex);
		}
	});
	
	return maxTabIndex;
}



function FixesAccesibilidadHermes() {

    // #region fix A sin href ni atributo role

    //acordeones de Bootstrap cuyo html cambia en el cliente y que por tanto se puede hacer el fix en el código
    var lista = $('a:not([href]):not([role])');
    //alert(lista.length);
    lista.attr("role", "link");
	

    // #endregion
    

    // #regionThe navigation role is unnecessary for element nav.
    lista = $('nav[role]');
    lista.removeAttr('role');
    // #endregion
	
	
	FixLinksRepetidosSlickVerMas();
	
	
	//FixTabIndexEnCeroOMenor();
	//FixLinksSinTabIndex();
}

function FixesUsabilidadHermes() {
    //#region, Usability.gov 13:12
    var selectsWithMoreThanTenOptions = $('select').filter(function () {
        return $(this).find('option').length > 10;
    });

    selectsWithMoreThanTenOptions.each(function () {
        CrearOptionsGroupAccesibilidad($(this));
    });
    // #endregion
}


var SetupAccessFix = function () {
	//si la imagen no tiene alt o esta vacío, y la imagen esta dentro un anchor que si tiene alt, entonces lo asigna
	$('img').each(function() {
		// Verifica si la imagen no tiene el atributo alt o si está vacío
		if (!$(this).attr('alt') || $(this).attr('alt') === '') {
			// Verifica si la imagen está dentro de un anchor
			var parentAnchor = $(this).closest('a');
			if (parentAnchor.length > 0) {
				// Si el anchor tiene un atributo aria-label o title, úsalo como alt para la imagen
				var anchorAlt = parentAnchor.attr('aria-label') || parentAnchor.attr('title');
				if (anchorAlt) {
					$(this).attr('alt', anchorAlt);
				}
			}
		}
	});
	//remueve la etiqueta border de las imagenes con efecto HOVER, por temas de accesibilidad
	$('figure img').removeAttr('border');
	/*
	enlaces que tienen target="_blank", y si el atributo href no empieza con http o https, ni contiene www,
	entonces quitará el atributo target="_blank" de esos enlaces.
	sí incluyen http o www, se añada el ariaWarning
	*/
	$('a[target="_blank"]').each(function() {
		var link = $(this);
		var href = link.attr('href');

		// Verificar si el href incluye 'http' o 'www'
		if (/^(http|https):\/\//.test(href) || href.includes('www')) {
			// Añadir advertencia mediante aria-describedby
			var ariaWarning = '<span id="new-window-warning" class="sr-only">Se abre en una nueva ventana</span>';
			link.attr('aria-describedby', 'new-window-warning');
			link.after(ariaWarning);
		} else {
			// Quitar el atributo target="_blank"
			link.removeAttr('target');
		}
	});
	/*fuerza el color de letra y fondo del footer para accesibilidad*/
 //   $('.AppContainer').each(function() {
 //       $(this).attr('style', 'background: #999 !important; color: #000 !important;');
 //   });
	//$('.AppContainer a').each(function() {
 //       $(this).attr('style', 'background: #999 !important; color: #000 !important; font-weight: 900 !important;');
 //   });
 
  	//para los html de gaceta
	$('span').removeAttr('lang');
	

	FixesAccesibilidadHermes();
		
}

;
/*
* onScreen 0.0.0
* Checks if matched elements are inside the viewport.
* Built on Mon Mar 09 2015 12:00:07
*
* Copyright 2015 Silvestre Herrera <silvestre.herrera@gmail.com> and contributors, Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* You can find a list of contributors at:
* https://github.com/silvestreh/onScreen/graphs/contributors
*/


!function(a){a.fn.onScreen=function(b){var c={container:window,direction:"vertical",toggleClass:null,doIn:null,doOut:null,tolerance:0,throttle:null,lazyAttr:null,lazyPlaceholder:"data:image/gif;base64,R0lGODlhEAAFAIAAAP///////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJCQAAACwAAAAAEAAFAAACCIyPqcvtD00BACH5BAkJAAIALAAAAAAQAAUAgfT29Pz6/P///wAAAAIQTGCiywKPmjxUNhjtMlWrAgAh+QQJCQAFACwAAAAAEAAFAIK8urzc2tzEwsS8vrzc3tz///8AAAAAAAADFEiyUf6wCEBHvLPemIHdTzCMDegkACH5BAkJAAYALAAAAAAQAAUAgoSChLS2tIyKjLy+vIyOjMTCxP///wAAAAMUWCQ09jAaAiqQmFosdeXRUAkBCCUAIfkECQkACAAsAAAAABAABQCDvLq83N7c3Nrc9Pb0xMLE/P78vL68/Pr8////AAAAAAAAAAAAAAAAAAAAAAAAAAAABCEwkCnKGbegvQn4RjGMx8F1HxBi5Il4oEiap2DcVYlpZwQAIfkECQkACAAsAAAAABAABQCDvLq85OLkxMLE9Pb0vL685ObkxMbE/Pr8////AAAAAAAAAAAAAAAAAAAAAAAAAAAABCDwnCGHEcIMxPn4VAGMQNBx0zQEZHkiYNiap5RaBKG9EQAh+QQJCQAJACwAAAAAEAAFAIOEgoTMysyMjozs6uyUlpSMiozMzsyUkpTs7uz///8AAAAAAAAAAAAAAAAAAAAAAAAEGTBJiYgoBM09DfhAwHEeKI4dGKLTIHzCwEUAIfkECQkACAAsAAAAABAABQCDvLq85OLkxMLE9Pb0vL685ObkxMbE/Pr8////AAAAAAAAAAAAAAAAAAAAAAAAAAAABCAQSTmMEGaco8+UBSACwWBqHxKOJYd+q1iaXFoRRMbtEQAh+QQJCQAIACwAAAAAEAAFAIO8urzc3tzc2tz09vTEwsT8/vy8vrz8+vz///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAEIhBJWc6wJZAtJh3gcRBAaXiIZV2kiRbgNZbA6VXiUAhGL0QAIfkECQkABgAsAAAAABAABQCChIKEtLa0jIqMvL68jI6MxMLE////AAAAAxRoumxFgoxGCbiANos145e3DJcQJAAh+QQJCQAFACwAAAAAEAAFAIK8urzc2tzEwsS8vrzc3tz///8AAAAAAAADFFi6XCQwtCmAHbPVm9kGWKcEQxkkACH5BAkJAAIALAAAAAAQAAUAgfT29Pz6/P///wAAAAIRlI8SAZsPYnuJMUCRnNksWwAAOw==",debug:!1};return"remove"!==b&&a.extend(c,b),"check"!==b&&a.extend(c,b),this.each(function(){function d(){a(l).off("scroll.onScreen resize.onScreen"),a(window).off("resize.onScreen")}function e(){return z?v<r-c.tolerance&&m<v+t-c.tolerance:v<p-c.tolerance&&v>-t+c.tolerance}function f(){return z?v+(t-c.tolerance)<m||v>r-c.tolerance:v>p-c.tolerance||-t+c.tolerance>v}function g(){return z?w<s-c.tolerance&&n<w+u-c.tolerance:w<q-c.tolerance&&w>-u+c.tolerance}function h(){return z?w+(u-c.tolerance)<n||w>s-c.tolerance:w>q-c.tolerance||-u+c.tolerance>w}function i(){return x?!1:"horizontal"===c.direction?g():e()}function j(){return x?"horizontal"===c.direction?h():f():!1}function k(a,b,c){var d,e,f;return function(){e=arguments,f=!0,c=c||this,d||!function(){f?(a.apply(c,e),f=!1,d=setTimeout(arguments.callee,b)):d=null}()}}var l=this;if("remove"===b)return void d();var m,n,o,p,q,r,s,t,u,v,w,x=!1,y=a(this),z=a.isWindow(c.container),A=function(){if(z||"static"!==a(c.container).css("position")||a(c.container).css("position","relative"),o=a(c.container),p=o.height(),q=o.width(),r=o.scrollTop()+p,s=o.scrollLeft()+q,t=y.outerHeight(!0),u=y.outerWidth(!0),z){var d=y.offset();v=d.top,w=d.left}else{var e=y.position();v=e.top,w=e.left}if(m=o.scrollTop(),n=o.scrollLeft(),c.debug,i()){if(c.toggleClass&&y.addClass(c.toggleClass),a.isFunction(c.doIn)&&c.doIn.call(y[0]),c.lazyAttr&&"IMG"===y.prop("tagName")){var f=y.attr(c.lazyAttr);f!==y.prop("src")&&(y.css({background:"url("+c.lazyPlaceholder+") 50% 50% no-repeat",minHeight:"5px",minWidth:"16px"}),y.prop("src",f).load(function(){a(this).css({background:"none"})}))}x=!0}else j()&&(c.toggleClass&&y.removeClass(c.toggleClass),a.isFunction(c.doOut)&&c.doOut.call(y[0]),x=!1);return"check"===b?x:void 0};window.location.hash?k(A,50):A(),c.throttle&&(A=k(A,c.throttle)),a(c.container).on("scroll.onScreen resize.onScreen",A),z||a(window).on("resize.onScreen",A),"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=jQuery:"function"==typeof define&&define.amd&&define("jquery-onscreen",[],function(){return jQuery})})}}(jQuery);
//# sourceMappingURL=jquery.onscreen.min.js.map;
