/* Minification failed. Returning unminified contents.
(2387,9-10): run-time error JS1014: Invalid character: `
(2387,56-57): run-time error JS1014: Invalid character: `
(2395,9-10): run-time error JS1014: Invalid character: `
(2395,10-11): run-time error JS1195: Expected expression: <
(2395,95-96): run-time error JS1195: Expected expression: >
(2395,113-114): run-time error JS1004: Expected ';': {
(2395,128-129): run-time error JS1195: Expected expression: <
(2395,132-133): run-time error JS1014: Invalid character: `
(2401,17-18): run-time error JS1014: Invalid character: `
(2401,18-19): run-time error JS1195: Expected expression: <
(2404,17-18): run-time error JS1195: Expected expression: <
(2404,21-22): run-time error JS1014: Invalid character: `
(2406,10-11): run-time error JS1195: Expected expression: )
(2408,5-9): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
(2408,10-11): run-time error JS1197: Too many errors. The file might not be a JavaScript file: {
 */
/*! @preserve
 * numeral.js
 * version : 2.0.6
 * author : Adam Draper
 * license : MIT
 * http://adamwdraper.github.com/Numeral-js/
 */
!function(a,b){"function"==typeof define&&define.amd?define(b):"object"==typeof module&&module.exports?module.exports=b():a.numeral=b()}(this,function(){function a(a,b){this._input=a,this._value=b}var b,c,d="2.0.6",e={},f={},g={currentLocale:"en",zeroFormat:null,nullFormat:null,defaultFormat:"0,0",scalePercentBy100:!0},h={currentLocale:g.currentLocale,zeroFormat:g.zeroFormat,nullFormat:g.nullFormat,defaultFormat:g.defaultFormat,scalePercentBy100:g.scalePercentBy100};return b=function(d){var f,g,i,j;if(b.isNumeral(d))f=d.value();else if(0===d||"undefined"==typeof d)f=0;else if(null===d||c.isNaN(d))f=null;else if("string"==typeof d)if(h.zeroFormat&&d===h.zeroFormat)f=0;else if(h.nullFormat&&d===h.nullFormat||!d.replace(/[^0-9]+/g,"").length)f=null;else{for(g in e)if(j="function"==typeof e[g].regexps.unformat?e[g].regexps.unformat():e[g].regexps.unformat,j&&d.match(j)){i=e[g].unformat;break}i=i||b._.stringToNumber,f=i(d)}else f=Number(d)||null;return new a(d,f)},b.version=d,b.isNumeral=function(b){return b instanceof a},b._=c={numberToFormat:function(a,c,d){var e,g,h,i,j,k,l,m=f[b.options.currentLocale],n=!1,o=!1,p=0,q="",r=1e12,s=1e9,t=1e6,u=1e3,v="",w=!1;if(a=a||0,g=Math.abs(a),b._.includes(c,"(")?(n=!0,c=c.replace(/[\(|\)]/g,"")):(b._.includes(c,"+")||b._.includes(c,"-"))&&(j=b._.includes(c,"+")?c.indexOf("+"):0>a?c.indexOf("-"):-1,c=c.replace(/[\+|\-]/g,"")),b._.includes(c,"a")&&(e=c.match(/a(k|m|b|t)?/),e=e?e[1]:!1,b._.includes(c," a")&&(q=" "),c=c.replace(new RegExp(q+"a[kmbt]?"),""),g>=r&&!e||"t"===e?(q+=m.abbreviations.trillion,a/=r):r>g&&g>=s&&!e||"b"===e?(q+=m.abbreviations.billion,a/=s):s>g&&g>=t&&!e||"m"===e?(q+=m.abbreviations.million,a/=t):(t>g&&g>=u&&!e||"k"===e)&&(q+=m.abbreviations.thousand,a/=u)),b._.includes(c,"[.]")&&(o=!0,c=c.replace("[.]",".")),h=a.toString().split(".")[0],i=c.split(".")[1],k=c.indexOf(","),p=(c.split(".")[0].split(",")[0].match(/0/g)||[]).length,i?(b._.includes(i,"[")?(i=i.replace("]",""),i=i.split("["),v=b._.toFixed(a,i[0].length+i[1].length,d,i[1].length)):v=b._.toFixed(a,i.length,d),h=v.split(".")[0],v=b._.includes(v,".")?m.delimiters.decimal+v.split(".")[1]:"",o&&0===Number(v.slice(1))&&(v="")):h=b._.toFixed(a,0,d),q&&!e&&Number(h)>=1e3&&q!==m.abbreviations.trillion)switch(h=String(Number(h)/1e3),q){case m.abbreviations.thousand:q=m.abbreviations.million;break;case m.abbreviations.million:q=m.abbreviations.billion;break;case m.abbreviations.billion:q=m.abbreviations.trillion}if(b._.includes(h,"-")&&(h=h.slice(1),w=!0),h.length<p)for(var x=p-h.length;x>0;x--)h="0"+h;return k>-1&&(h=h.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+m.delimiters.thousands)),0===c.indexOf(".")&&(h=""),l=h+v+(q?q:""),n?l=(n&&w?"(":"")+l+(n&&w?")":""):j>=0?l=0===j?(w?"-":"+")+l:l+(w?"-":"+"):w&&(l="-"+l),l},stringToNumber:function(a){var b,c,d,e=f[h.currentLocale],g=a,i={thousand:3,million:6,billion:9,trillion:12};if(h.zeroFormat&&a===h.zeroFormat)c=0;else if(h.nullFormat&&a===h.nullFormat||!a.replace(/[^0-9]+/g,"").length)c=null;else{c=1,"."!==e.delimiters.decimal&&(a=a.replace(/\./g,"").replace(e.delimiters.decimal,"."));for(b in i)if(d=new RegExp("[^a-zA-Z]"+e.abbreviations[b]+"(?:\\)|(\\"+e.currency.symbol+")?(?:\\))?)?$"),g.match(d)){c*=Math.pow(10,i[b]);break}c*=(a.split("-").length+Math.min(a.split("(").length-1,a.split(")").length-1))%2?1:-1,a=a.replace(/[^0-9\.]+/g,""),c*=Number(a)}return c},isNaN:function(a){return"number"==typeof a&&isNaN(a)},includes:function(a,b){return-1!==a.indexOf(b)},insert:function(a,b,c){return a.slice(0,c)+b+a.slice(c)},reduce:function(a,b){if(null===this)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof b)throw new TypeError(b+" is not a function");var c,d=Object(a),e=d.length>>>0,f=0;if(3===arguments.length)c=arguments[2];else{for(;e>f&&!(f in d);)f++;if(f>=e)throw new TypeError("Reduce of empty array with no initial value");c=d[f++]}for(;e>f;f++)f in d&&(c=b(c,d[f],f,d));return c},multiplier:function(a){var b=a.toString().split(".");return b.length<2?1:Math.pow(10,b[1].length)},correctionFactor:function(){var a=Array.prototype.slice.call(arguments);return a.reduce(function(a,b){var d=c.multiplier(b);return a>d?a:d},1)},toFixed:function(a,b,c,d){var e,f,g,h,i=a.toString().split("."),j=b-(d||0);return e=2===i.length?Math.min(Math.max(i[1].length,j),b):j,g=Math.pow(10,e),h=(c(a+"e+"+e)/g).toFixed(e),d>b-e&&(f=new RegExp("\\.?0{1,"+(d-(b-e))+"}$"),h=h.replace(f,"")),h}},b.options=h,b.formats=e,b.locales=f,b.locale=function(a){return a&&(h.currentLocale=a.toLowerCase()),h.currentLocale},b.localeData=function(a){if(!a)return f[h.currentLocale];if(a=a.toLowerCase(),!f[a])throw new Error("Unknown locale : "+a);return f[a]},b.reset=function(){for(var a in g)h[a]=g[a]},b.zeroFormat=function(a){h.zeroFormat="string"==typeof a?a:null},b.nullFormat=function(a){h.nullFormat="string"==typeof a?a:null},b.defaultFormat=function(a){h.defaultFormat="string"==typeof a?a:"0.0"},b.register=function(a,b,c){if(b=b.toLowerCase(),this[a+"s"][b])throw new TypeError(b+" "+a+" already registered.");return this[a+"s"][b]=c,c},b.validate=function(a,c){var d,e,f,g,h,i,j,k;if("string"!=typeof a&&(a+="",console.warn&&console.warn("Numeral.js: Value is not string. It has been co-erced to: ",a)),a=a.trim(),a.match(/^\d+$/))return!0;if(""===a)return!1;try{j=b.localeData(c)}catch(l){j=b.localeData(b.locale())}return f=j.currency.symbol,h=j.abbreviations,d=j.delimiters.decimal,e="."===j.delimiters.thousands?"\\.":j.delimiters.thousands,k=a.match(/^[^\d]+/),null!==k&&(a=a.substr(1),k[0]!==f)?!1:(k=a.match(/[^\d]+$/),null!==k&&(a=a.slice(0,-1),k[0]!==h.thousand&&k[0]!==h.million&&k[0]!==h.billion&&k[0]!==h.trillion)?!1:(i=new RegExp(e+"{2}"),a.match(/[^\d.,]/g)?!1:(g=a.split(d),g.length>2?!1:g.length<2?!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i):1===g[0].length?!!g[0].match(/^\d+$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/):!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/))))},b.fn=a.prototype={clone:function(){return b(this)},format:function(a,c){var d,f,g,i=this._value,j=a||h.defaultFormat;if(c=c||Math.round,0===i&&null!==h.zeroFormat)f=h.zeroFormat;else if(null===i&&null!==h.nullFormat)f=h.nullFormat;else{for(d in e)if(j.match(e[d].regexps.format)){g=e[d].format;break}g=g||b._.numberToFormat,f=g(i,j,c)}return f},value:function(){return this._value},input:function(){return this._input},set:function(a){return this._value=Number(a),this},add:function(a){function b(a,b,c,e){return a+Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([this._value,a],b,0)/d,this},subtract:function(a){function b(a,b,c,e){return a-Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([a],b,Math.round(this._value*d))/d,this},multiply:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)*Math.round(b*f)/Math.round(f*f)}return this._value=c.reduce([this._value,a],b,1),this},divide:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)/Math.round(b*f)}return this._value=c.reduce([this._value,a],b),this},difference:function(a){return Math.abs(b(this._value).subtract(a).value())}},b.register("locale","en",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(a){var b=a%10;return 1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th"},currency:{symbol:"$"}}),function(){b.register("format","bps",{regexps:{format:/(BPS)/,unformat:/(BPS)/},format:function(a,c,d){var e,f=b._.includes(c," BPS")?" ":"";return a=1e4*a,c=c.replace(/\s?BPS/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"BPS"),e=e.join("")):e=e+f+"BPS",e},unformat:function(a){return+(1e-4*b._.stringToNumber(a)).toFixed(15)}})}(),function(){var a={base:1e3,suffixes:["B","KB","MB","GB","TB","PB","EB","ZB","YB"]},c={base:1024,suffixes:["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]},d=a.suffixes.concat(c.suffixes.filter(function(b){return a.suffixes.indexOf(b)<0})),e=d.join("|");e="("+e.replace("B","B(?!PS)")+")",b.register("format","bytes",{regexps:{format:/([0\s]i?b)/,unformat:new RegExp(e)},format:function(d,e,f){var g,h,i,j,k=b._.includes(e,"ib")?c:a,l=b._.includes(e," b")||b._.includes(e," ib")?" ":"";for(e=e.replace(/\s?i?b/,""),h=0;h<=k.suffixes.length;h++)if(i=Math.pow(k.base,h),j=Math.pow(k.base,h+1),null===d||0===d||d>=i&&j>d){l+=k.suffixes[h],i>0&&(d/=i);break}return g=b._.numberToFormat(d,e,f),g+l},unformat:function(d){var e,f,g=b._.stringToNumber(d);if(g){for(e=a.suffixes.length-1;e>=0;e--){if(b._.includes(d,a.suffixes[e])){f=Math.pow(a.base,e);break}if(b._.includes(d,c.suffixes[e])){f=Math.pow(c.base,e);break}}g*=f||1}return g}})}(),function(){b.register("format","currency",{regexps:{format:/(\$)/},format:function(a,c,d){var e,f,g,h=b.locales[b.options.currentLocale],i={before:c.match(/^([\+|\-|\(|\s|\$]*)/)[0],after:c.match(/([\+|\-|\)|\s|\$]*)$/)[0]};for(c=c.replace(/\s?\$\s?/,""),e=b._.numberToFormat(a,c,d),a>=0?(i.before=i.before.replace(/[\-\(]/,""),i.after=i.after.replace(/[\-\)]/,"")):0>a&&!b._.includes(i.before,"-")&&!b._.includes(i.before,"(")&&(i.before="-"+i.before),g=0;g<i.before.length;g++)switch(f=i.before[g]){case"$":e=b._.insert(e,h.currency.symbol,g);break;case" ":e=b._.insert(e," ",g+h.currency.symbol.length-1)}for(g=i.after.length-1;g>=0;g--)switch(f=i.after[g]){case"$":e=g===i.after.length-1?e+h.currency.symbol:b._.insert(e,h.currency.symbol,-(i.after.length-(1+g)));break;case" ":e=g===i.after.length-1?e+" ":b._.insert(e," ",-(i.after.length-(1+g)+h.currency.symbol.length-1))}return e}})}(),function(){b.register("format","exponential",{regexps:{format:/(e\+|e-)/,unformat:/(e\+|e-)/},format:function(a,c,d){var e,f="number"!=typeof a||b._.isNaN(a)?"0e+0":a.toExponential(),g=f.split("e");return c=c.replace(/e[\+|\-]{1}0/,""),e=b._.numberToFormat(Number(g[0]),c,d),e+"e"+g[1]},unformat:function(a){function c(a,c,d,e){var f=b._.correctionFactor(a,c),g=a*f*(c*f)/(f*f);return g}var d=b._.includes(a,"e+")?a.split("e+"):a.split("e-"),e=Number(d[0]),f=Number(d[1]);return f=b._.includes(a,"e-")?f*=-1:f,b._.reduce([e,Math.pow(10,f)],c,1)}})}(),function(){b.register("format","ordinal",{regexps:{format:/(o)/},format:function(a,c,d){var e,f=b.locales[b.options.currentLocale],g=b._.includes(c," o")?" ":"";return c=c.replace(/\s?o/,""),g+=f.ordinal(a),e=b._.numberToFormat(a,c,d),e+g}})}(),function(){b.register("format","percentage",{regexps:{format:/(%)/,unformat:/(%)/},format:function(a,c,d){var e,f=b._.includes(c," %")?" ":"";return b.options.scalePercentBy100&&(a=100*a),c=c.replace(/\s?\%/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"%"),e=e.join("")):e=e+f+"%",e},unformat:function(a){var c=b._.stringToNumber(a);return b.options.scalePercentBy100?.01*c:c}})}(),function(){b.register("format","time",{regexps:{format:/(:)/,unformat:/(:)/},format:function(a,b,c){var d=Math.floor(a/60/60),e=Math.floor((a-60*d*60)/60),f=Math.round(a-60*d*60-60*e);return d+":"+(10>e?"0"+e:e)+":"+(10>f?"0"+f:f)},unformat:function(a){var b=a.split(":"),c=0;return 3===b.length?(c+=60*Number(b[0])*60,c+=60*Number(b[1]),c+=Number(b[2])):2===b.length&&(c+=60*Number(b[0]),c+=Number(b[1])),Number(c)}})}(),b});;
// numeral.js locale configuration
// locale : spanish Spain
// author : Hernan Garcia : https://github.com/hgarcia

(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['../numeral'], factory);
    } else if (typeof module === 'object' && module.exports) {
        factory(require('../numeral'));
    } else {
        factory(global.numeral);
    }
}(this, function (numeral) {
    numeral.register('locale', 'es-cr', {
        delimiters: {
            thousands: '.',
            decimal: ','
        },
        abbreviations: {
            thousand: 'k',
            million: 'mm',
            billion: 'b',
            trillion: 't'
        },
        ordinal: function (number) {
            var b = number % 10;
            return (b === 1 || b === 3) ? 'er' :
                (b === 2) ? 'do' :
                    (b === 7 || b === 0) ? 'mo' :
                        (b === 8) ? 'vo' :
                            (b === 9) ? 'no' : 'to';
        },
        currency: {
            symbol: '₡'
        }
    });
}));
;
var CreateBodyOverlay = function () {
  $("<div class='bodyOverlay' />")
    .css({
      position: "absolute",
      width: "100%",
      height: "100%",
      left: 0,
      top: 0,
      zIndex: 999, // to be on the safe side
      background: "#fff url('/images/pageLoading.gif') center 200px no-repeat",
    })
    .appendTo(
      jQuery("body").css({
        position: "relative",
        opacity: 1,
      })
    );
};

var RemoveBodyOverlay = function () {
  jQuery(".bodyOverlay").fadeOut(500, function () {
    jQuery(this).remove();
  });
};

//Se crea el Overlay
CreateBodyOverlay();

$(window).on("load", function () {
  jQuery("#MainContainer").animate({ opacity: 1 }, 500);
  setTimeout(function () {
    RemoveBodyOverlay();
  }, 10);
});
;
// *** 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);
}


numeral.locale('es-cr');
function FormatearMoneda(val, simbolo) {
    if (typeof (val) == "string" && !isNaN(val)) {
        val = val * 1;
    } else if (typeof (val) == "string" && !val.match(/^-?\d+([\,\.]\d+)*$/)) {
        return val;
    }

    var simboloOriginal = null;
    if (simbolo !== undefined) {
        simboloOriginal = numeral.localeData().currency.symbol;
        numeral.localeData().currency.symbol = simbolo;
    }

    var strFormateado = numeral(val).format('$ 0,0.00');

    if (simboloOriginal) {
        numeral.localeData().currency.symbol = simboloOriginal;
    }
    return strFormateado;
};
var SQLFORMATOFECHAMASESTANDAR = "yyyyMMdd";
var MASKMONEY_FORMAT = '#.##0,00';

var fileToUpload;

function Select2Helper(selector, jsonParam) {
    this.combo = $(selector);
    this.json = jsonParam;
    this.ordenado = [];

    this.IncluirHijos = function (elem) {
        elem.tieneHijos = false;

        for (var i = 0; i < this.json.length; i++) {
            if (this.json[i].idCatalogoCuentaPadre == elem.idCatalogoCuenta) {
                elem.tieneHijos = true;
                this.ordenado.push(this.json[i]);
                this.IncluirHijos(this.json[i])
                //delete this.json[i];
            }
        }
    }

    this.Populate = function () {
        //ordenar
        var option;
        var elem;
        var className;

        for (var i = 0; i < this.json.length; i++) {
            elem = this.json[i];

            if (elem.idCatalogoCuentaPadre == null) {
                this.ordenado.push(elem);
                this.IncluirHijos(elem);
                //delete this.json[i];
            }
        }

        //procesar ordenado                
        for (var i = 0; i < this.ordenado.length; i++) {
            elem = this.ordenado[i];
            option = new Option(elem.codigoCatalogoCuenta + ' ' + elem.descripcionCatalogoCuenta, elem.idCatalogoCuenta);

            this.combo.append(option);

            if (elem.idCatalogoCuentaPadre != null) {
                //<option value="11" data-pup="1" class="l2 non-leaf">opt_11</option>
                $(option).attr("data-pup", elem.idCatalogoCuentaPadre);
            }

            className = "l" + elem.nivel;
            $(option).addClass(className);

            if (elem.tieneHijos) {
                $(option).addClass("non-leaf");
            }
        }

        $(".non-leaf").prop("disabled", "disabled");
    }
}


function LoadPageInModalIframe(url, ModalMultiUsoTitle, onClose) {
    $('#divIframe').hide();
    $('#divImgLoading').show();

    $('#ModalMultiUsoTitle').html(ModalMultiUsoTitle);

    $('#divIframe').load(function () {
        $('#divImgLoading').hide();
        $(this).show();
    });

    $('#divIframe').prop("src", url);


    $('#ModalMultiUso').on('hidden.bs.modal', function () {

        if (onClose)
            onClose();

        $('#divIframe').prop("src", "");

        $('#ModalMultiUso').off('hidden.bs.modal');
    })
}

function GetUrlTareasAvaluo() {
    var idObjeto = $("#IdObjetoSeleccionadoHiddenField").val(); 
    var s = _AppRoot + '/controlpanel/ordentrabajo/PopupResultadoAvaluo.aspx?idObjeto=' + idObjeto;
    
    return s;
}

function VerTareasDeAvaluo()
{
    $("#VerTareasAValueLink").click();
}

function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    fileToUpload = (evt.dataTransfer || evt.currentTarget).files[0]; // div o input

    $('.DTE_Form_Buttons .btn').prop("disabled", "disabled");

    if (fileToUpload.size > maxSizeAnexoEnMB * Math.pow(2, 20)) {
        $('.DTE_Form_Buttons .btn').prop("enabled", false);
        ErrorMessage('Excede el tamaño permitido de ' + maxSizeAnexoEnMB + ' MB');
        return;
    }



    if ($('#progressBar').length == 0) {
        $('.drop').before('<div id="tempUploadDiv"><strong><span id="fileSizeDiv"></span></strong>' +
            '<a id="SubirArchivoDatatableLink" href="#" onclick="uploadFiles(); return false;">subir</a> ' +
            '<input type="hidden" id="fileToUploadID" name="fileToUploadID" /> ' +

            '<div class="progress"><div id="progressBar" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div></div>' +
            '</div>'
        );

    }

    $('#fileSizeDiv').html(Math.round(fileToUpload.size / Math.pow(2, 20)) + ' MB.   ');

    $("#SubirArchivoDatatableLink").show();
}

function handleDragOver(evt) {


    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}

function setProcessBarValue(selector, loaded, total) {
    var percent = Math.round((loaded / total) * 100);

    if (percent == Infinity)
        percent == 100;

    var texto = (total == 100 && loaded == 0) ? "0" :
        percent + "% (" + Math.round(loaded / Math.pow(2, 20)) + " de " + Math.round(total / Math.pow(2, 20)) + " MB)"

    texto = texto.replace("(0 de 0 MB)", ""); //fix para cantidad menors a MB

    if (texto == "Infinity%")
    {
        texto = "Completado";
    }

    $(selector).css("width", percent + "%")
        .attr("aria-valuenow", percent)
        .text(texto);
}

function uploadFiles() {
    // START A LOADING SPINNER HERE

    // Create a formdata object and add the files
    var data = new FormData();
    data.append("file", fileToUpload);//solo el primero

    //$.each(files, function (key, value) {
    //    data.append(key, value);
    //});

    $.ajax({
        url: _AppRoot + '/App_HttpHandlers/tempUpload.ashx',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function (data, textStatus, jqXHR) {
            $("#SubirArchivoDatatableLink").hide();                   

            if (!data.message) {
                // Success so call function to process the form
                //submitForm(event, data);

                $("#fileToUploadID").val(data.id);
                var input = $('input[type="file"]');

                $('.DTE_Form_Buttons .btn').removeProp("disabled"); 

                //ya se envío el archivo entonces limpiar
                input.replaceWith(input.val('').clone(true)); //https://stackoverflow.com/questions/20549241/how-to-reset-input-type-file                               
            }
            else {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
                alert('ERRORS: ' + data.error);
                $("#datos").html(jqXHR.responseText);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            debugger;
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
            alert('ERRORS: ' + textStatus)
            $("#datos").html(jqXHR.responseText);
            // STOP LOADING SPINNER
        },
        progress: function (event) {
            setProcessBarValue("#progressBar", event.loaded, event.total);    
        },
    });
}


/* 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('#HideButton');
            },
            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 () {
        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").remove();
    jQuery(":submit").not(".BotonVisible,.ControlVisible").remove();

    // 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) {
    jQuery(selector).not(".ControlVisible").each(function (i) {
        var selectedItemText = "";
        var control = jQuery(this);
        var cssClass = "textControl";
        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.remove();
                }
                else {
                    // busca el <label> asociado y lo remueve
                    jQuery('label[for=' + control.attr("id") + ']').remove();
                }
            }

            // reemplaza el control por un <span>
            control.replaceWith("<span id='" + control.attr("name") + "' class=\"" + cssClass + "\"" + ariaHidden + ">" + selectedItemText + "</span>");

        }
        else { }
    });
}

function ReemplazarControlAccessiblePorTexto(control) {
    var texto = "";

    if (control.is("select")) {
        texto = $("option:selected", control).text();
    }
    else if (control.is("input")) {
        texto = control.val();
    }
    // else if ...

    control.next("span.temporal").remove();

    var span = $("<span />")
        .addClass("textControl")
        .addClass("temporal")
        .html(texto);

    control.after(span);
    control.addClass("hidden-accessible");
}

function RestaurarControlAccessible(control) {
    control.next("span.temporal").remove();
    control.removeClass("hidden-accessible");
}

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 = 'ViewAuditoria.key2';
            key2Value = key2;
        }
        $('#ViewAuditoriaTable').customeditor({
            dataTablesKey: "MantenimientoViewAuditoria",
            readOnly: true,
            dataTablesColumns:
            [
                    { data: 'ViewAuditoria.id' },
                    { data: 'ViewAuditoria.fechahora' },
                {
                    data: 'ViewAuditoria.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: 'ViewAuditoria.idUser' },
                    { data: 'ViewAuditoria.ip' },
                {
                    data: 'ViewAuditoria.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: 'ViewAuditoria.key1', value: key1, operator: '=' },
                { key: key2Filtro, value: key2Value, operator: '=' },
                { key: 'ViewAuditoria.objeto', value: objeto, operator: '=' }
            ]
        });

        // get plugin data
        var viewAuditoriaPluginData = $('#ViewAuditoriaTable').customeditor('getData');

        // update filters
        viewAuditoriaPluginData.filters = [
            { key: 'ViewAuditoria.key1', value: key1, operator: '=' },
            { key: key2Filtro, value: key2Value, operator: '=' },
            { key: 'ViewAuditoria.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 = false;

//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 "";
}

// IsoDateString() = DateTime.Now
// IsoDateString('2020-09-24') = 24/09/2020
function IsoDateString(datetime) {
    var d = new Date();
    if (datetime !== 'undefined') {
        d = new Date(date);
    }
    var pad = function (n) {
        return n < 10 ? '0' + n : n
    }

    return pad(d.getUTCDate()) + '/'
        + pad(d.getUTCMonth() + 1) + '/'
        + pad(d.getUTCFullYear())
};


// IsoDateTimeString() = DateTime.Now
// IsoDateTimeString('2020-09-24 09:00:34.817') = 24/09/2020 09:04 AM
function IsoDateTimeString(datetime) {
    
    var d = new Date();
    if (datetime !== 'undefined') {
        d = new Date(datetime);
    }

    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 InitJQueryMask() {

    jQuery('.maskMoney').mask(MASKMONEY_FORMAT,
        {
            reverse: true
        });
}

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;
}

function GetIdObjetoSeleccionado() {
    var idObjeto = $("#IdObjetoSeleccionadoHiddenField").val();
    return idObjeto;
}

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);
    });
}


function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

Date.prototype.addDays = function (days) {
    var ms = this.getTime() + (86400000 * days);
    var added = new Date(ms);
    return added;
}


jQuery.beforeReadyPrivateArray = []
jQuery.beforeReady = function (handler) {
    jQuery.beforeReadyPrivateArray.push(handler)
}

$(function () {
    var arrayLength = jQuery.beforeReadyPrivateArray.length;
    for (var i = 0; i < arrayLength; i++) {
        jQuery.beforeReadyPrivateArray[i]()
    }
})

function SetEditorFieldVisibility(editor, field, visible) {
    if (visible)
        editor.field(field).show();
    else
        editor.field(field).hide();
}

$(document).ready(function () {
    if (typeof $.fn.datepicker != "undefined") {
        InitDatepicker();
    }
    if (typeof $.fn.datetimepicker != "undefined") {
        InitDateTimePicker();
    }
    if (typeof $.fn.mask != "undefined") {
        InitJQueryMask();
    }

    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
        }
    }
});
;
// 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;");
    });
}
;
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";
  }
}
;
/////////////////////////////////
//TODO: Actualizar conrespecto a CNE
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 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(".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 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 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 a").css("font-size", "");
  jQuery(".WordSection1 span").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 a").css("font-size", "");
  jQuery(".MainContentPlaceDiv span").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 });
}
;
var SetupMegadropdowMenu = function () {
  //////FIXES megadropdown-menu ///////////////////////
  if (typeof fixMegadropdowMenu != "undefined" && fixMegadropdowMenu) {
    var navbarWidth = jQuery(".navbar-default").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" });
        }
      });
  }
};
;
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 =
        ".ResultadoReportViewer,.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 2:
                          colClass = "col-sm-6";
                          break;
                        case 3:
                          colClass = "col-sm-4";
                          break;
                        case 4:
                          colClass = "col-sm-3";
                          break;
                        case 6:
                          colClass = "col-sm-2";
                          break;
                        case 12:
                          colClass = "col-sm-1";
                          break;
                        default:
                          colClass = "col-sm";
                          break;
                      }*/
                    colClass += "col-sm overflow-hidden";

                    $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 + " overflow-hidden";
                        }
                        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,.NoticiasContainer"
                        ).length > 0
                    ) {
                        $newConvertedTable.append($newRow);
                    }
                });
                $currentTable.before($newConvertedTable);
                $currentTable.remove();
                jQuery("div[data-rowspan]").each(function () {
                    var $this = jQuery(this);
                    //console.log("fixLayout() " + $this.attr("data-rowspan"));
                });
            }
        });
    jQuery("table.HERMESIGNORETABLETOGRID").each(function () {
        var $thisTable = jQuery(this);
        $thisTable.find("table").addClass("w-100");
        var $tableContent = $thisTable
            .find("tr:nth-child(2) > td:first")
            .contents();

        $thisTable.after($tableContent);
        $thisTable.remove();
    });
}

var fixImagesForResponsive = function () {
    jQuery(".WordSection1 img,.nav img, #PageContent img")
        .not(".ImageZoom img, .free-wall img, .menuImage")
        .addClass("img-fluid")
        .removeAttr("width")
        .removeAttr("height");
};
;
var lastScrollUpdate = 0;
var SetupOnScroll = function() {
    jQuery(window).scroll(function() {
        var needsRefresh = new Date() - lastScrollUpdate > 2000;
        if (needsRefresh) {
            lastScrollUpdate = new Date();
        }

        if (needsRefresh && typeof AOS != "undefined") {
            AOS.refreshHard();
        }

        if (needsRefresh && typeof SectionBgRefresh != "undefined") {
            SectionBgRefresh();
        }

        if (jQuery(window).width() < 768) {
            return true;
        }

        var SbSiteHeight = jQuery("#sb-site").height();
        var BottomHeight = jQuery(".BottomSection").height();

        if ($(window).scrollTop() >= SbSiteHeight - (BottomHeight + 820)) {
            $(".backtotop").addClass("backtotopstatic");
        } else {
            $(".backtotop").removeClass("backtotopstatic");
        }

        //Menú flotante
        var scroll = jQuery(window).scrollTop();
        var jQuerywindow = jQuery(window);
        if (scroll >= 250) {
            jQuery(".redesContainer").addClass("flotante");
        } else {
            jQuery(".redesContainer").removeClass("flotante");
        }


        var SbSiteHeight = jQuery("#sb-site").height();
        var BottomHeight = jQuery(".completeFooter").height();

        if ($(window).scrollTop() >= SbSiteHeight - (BottomHeight + 650)) {
            $(".redesContainer").addClass("RedesContainerstatic");
        } else {
            $(".redesContainer").removeClass("RedesContainerstatic");
        }

        var FooterHeight = $(".FooterTag").height();
        //alert(FooterHeight);
        //if ($(window).scrollTop() + $(window).height() > $(document).height() - FooterHeight) {
        //    $(".backtotop").css("bottom", FooterHeight);
        //    $(".backtotop").addClass("backtotopstatic");
        //} else {
        //    $(".backtotop").css("bottom", 30);
        //    $(".backtotop").remove("backtotopstatic");
        //}
    });
};;
/*Ver PDF*/
function CambiarLinkPDF($this) {
  var nuevo = "/ver" + $this.attr("href");
  if (nuevo.toLowerCase().indexOf("verhttp") == -1) {
    $this.attr("href", nuevo);
  }
}

var SetupPaginaIntermedia = function () {
  jQuery("a[href$='.pdf']")
    .not(
      ".VerArchivo, a[href*='.aspx'],a[href*='.html'], a[rel^='lightbox'],.HASBreadCrumbs a"
    )
    .each(function () {
      var $this = jQuery(this);
      CambiarLinkPDF($this);
    });

  if (jQuery("#ficha, .FichaArchivoContainer").length == 0) {
    jQuery(".addOns").after("<div class='clear'></div>");
    var idpagina = jQuery("input[id$=idpagina]").val();
    if (idpagina) {
      jQuery.ajax({
        url: "/app_httphandlers/CategoriasPagina.ashx",
        data: { id: idpagina },
        success: function (data) {
          var $CategoriesContainer = jQuery("#CategoriesContainer");
          if ($CategoriesContainer.length > 0) {
            $CategoriesContainer.append(data);
          } /*else {
                                        jQuery(".MainContentPlaceDiv:first").after(data);
                                    }*/
          if (typeof $CategoriasPaginaDiv != "undefined") {
            $CategoriasPaginaDiv.show();
          }
        },
      });
    }
  }
};
;
////////////////////////////////
include("/js/jquery/jquery.transform.min.js", { dom: true });
function RenderRSSWidget(selector, currentXML, currentXSL) {
  if ($(selector).length == 0) return;
  $(selector).transform({
    xml: currentXML,
    xsl: currentXSL,
    complete: function () {
      LoadRSSWidgetSlick(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 LoadRSSWidgetSlick(selector) {
  var $RSSWidget = jQuery(selector);
  $RSSWidget.find(".noticiasticker,.rssticker").slick({
    dots: true,
    arrows: true,
    infinite: true,
    speed: 800,
    slidesToShow: 5,
    slidesToScroll: 1,
    autoplay: false,
    autoplaySpeed: 3000,
    responsive: [
      {
        breakpoint: 1400,
        settings: {
          slidesToShow: 4,
          slidesToScroll: 1,
        },
      },
      {
        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
    ],
  });

  setTimeout(function () {
    $RSSWidget.animate({ opacity: 1 }, 500);
    $(window).resize();
  }, 1000);
}

var SetupRSSWidget = function () {
  var NoticiasXmlFileDefault = "/noticias/rss.xml";
  var NoticiasXslFileDefault = "/xsl/noticias.xsl";
  var NoticiasXmlFile,
    NoticiasXslFile = "";
  $(".rssFeed").each(function (index) {
    var $self = $(this);

    $self.onScreen({
      container: window,
      direction: "vertical",
      doIn: function () {
        var ready = $self.data("ready");
        if(ready){
            return false;
        }

        var attrXML = $self.attr("data-xml");
        var attrXSL = $self.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;
        }
        $self.attr("id", $self.attr("id") + index);
        var ID = $("#" + $self.attr("id"));
        RenderRSSWidget(ID, NoticiasXmlFile, NoticiasXslFile);

        $self.data("ready",true);

        if (typeof SectionBgRefresh != "undefined") {
          SectionBgRefresh();
        }
      },
      doOut: function () {
        // Do something to the matched elements as they get off scren
      },
      tolerance: 0,
      throttle: 50,
      toggleClass: "onScreen",
      lazyAttr: null,
      lazyPlaceholder: "someImage.jpg",
      debug: false,
    });
  });
};
;
var SetupBuscador = function () {
  jQuery("#expresion").keypress(function (e) {
    if (e.which == 13) {
      jQuery("#botonBuscar").click();
    }
  });

  jQuery("#botonBuscar,#BuscarButtonMobile").click(function (e) {
    e.preventDefault();
    var form = $("#aspnetForm");
    form.prop("action", "/buscador/default.aspx");
    form.off();
    var vs = document.getElementById("__VIEWSTATE");
    if (typeof vs != "undefined") {
      vs.value = "";
    }
    form.submit();
  });  

  jQuery(".searchContainer .lupaBuscador").click(function () {
    if (jQuery(window).width() < 768) {
      return true;
    }
    $(this).parent().toggleClass("SearchModalInput");
    $(".SearchModal").addClass("SearchModalActive");
    $(".searchContainer .input-group").addClass("activo");
  });

  jQuery(".CloseSearchModal").click(function () {
    $(".SearchModalInput").removeClass("SearchModalInput");
    $(".SearchModal").removeClass("SearchModalActive");
  });
};
;
var SetupMultiLevelMenus = function () {
    var dropdowns = document.querySelectorAll(
        "nav.navbar .dropdown .nav-link.dropdown-toggle"
    );
    dropdowns.forEach(function (dropdown, idx) {
        dropdown.addEventListener("click", function (e) {
            var $this = $(this);
            var $liParent = $this.parent();

            e.stopPropagation();

            //abrir href de un item de menu con submenu
            //ojo muy truculento
            if (!$this.hasClass("show")) {
                var currentHref = $this.attr("href");
                if (currentHref && currentHref != '#') {
                    window.location = currentHref
                } else {
                    e.preventDefault();
                    return;
                }
            }

            //limpiamos los otros seleccionados
            document
                .querySelectorAll(
                    ".dropdown.show, .dropdown-menu.show, .dropdown-menu .dropdown-toggle.show"
                )
                .forEach(function (submenu) {
                    submenu.classList.remove("show");
                });
            $this.parents(".dropdown-menu").addClass("show");


            $this
                .parents(".dropdown")
                .find(".dropdown-toggle:first")
                .addClass("show")
                .attr("aria-expanded", "true");


            const element = $liParent[0].querySelector(".dropdown-menu");
            element.classList.add("show");
            var itemBounds = element.getBoundingClientRect();
            //console.log(itemBounds.right, window.innerWidth);

            if (itemBounds.right > window.innerWidth) {
                //console.log("El menu va para la izq");
                element.classList.add("menuLadoIzquierdo");
                //this.parents(".nav-item").classList.add("flechaIzquierda");
                this.classList.add("flechaIzquierda");
            }
        });
    });


    //determina cuando un menu se alinea a la derecha
    setTimeout(function () {
        $(".navbar-nav > .nav-item ").each(function () {
            var itemBounds = this.getBoundingClientRect();
            //console.log(itemBounds.right, window.innerWidth);
            if (itemBounds.right > window.innerWidth / 2) {
                this.classList.add("ladoDerecho");
            }
        });
    }, 500);


};
;
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;
}

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) {
                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 {
        $ChatList.before(
            `<div id="DatosIntermedios">
                <div class="DatosIntermediosContenedor">
					${item.respuesta}
				</div>
                <hr>
                <button class="btn btn-link" onclick="MostrarFormulario()">¿Encontró  lo que buscaba?</button>
            </div>`
        );
    }
}

function MostrarFormulario() {
    event.preventDefault();

    var $datos = $('#DatosIntermedios');
    $datos.empty();

    $datos.append(
        `<form id='FormularioAsistenteVirtual' class='mt-4'>
            <h3>Formulario de consulta</h3>
            <input type="hidden" name="doEncoding" value="false"/>
            <input type="hidden" name="IDTipoFormulario" value="1"/>
            <input type = "hidden" name = "DescripcionTipoFormulario" value = "FORMULARIO ASISTENTE VIRTUAL" />
            <br>
            <label for="nombre">Nombre completo:</label><br>
            <input type="text" id="nombre" name="nombre" required="required" value="" class="form-control">
            <label for="email">Correo:</label><br>
            <input type="email" id="email" required="required" class="form-control" name="email" placeholder="ejemplo@dominio.com" value="">
            <label for="consulta">Consulta:</label><br>
            <textarea required="required" name="consulta" id="consulta" class="form-control" placeholder="Ingrese su consulta"></textarea>
            <br><br>
            <input type="submit" value="Enviar" class="btn btn-primary" onclick="EnviarFormularioAsistenteVirtual(this)">
        </form>
        <div id="MensajeDiv"></div>`
    );
}


function ChangeOptionChat(next, url) {
    
    if (url != undefined && url != null && url != '') {

        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() {
    window.sessionStorage.removeItem('itemChat');
    $('#ChatHome').removeClass("active");
}

function TieneContenido(selector) {
    return $(selector).val().length > 0;
}

//Aqui se implementa el envio del formulario xxxxxxx
function EnviarFormularioAsistenteVirtual(boton) {
    var elBoton = $(boton);
   
    elBoton.prop("disabled", "disabled");

    event.preventDefault();

    if (TieneContenido("#nombre") && TieneContenido("#email") && TieneContenido("#consulta")) {


        var data = $('#FormularioAsistenteVirtual').serializeObject();

        //data = {
        //    campo1: '',
        //    campo1: ''
        //}

        console.log(data);
        EjecutarPostAjax(_AppRoot + '/App_HttpHandlers/FormularioAsistenteVirtualHandler.ashx', data)
            .then((response) => {
                console.log(response);
                $("#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>'
                    */
                );
                $("#FormularioAsistenteVirtual").remove();
            });
    }
    else {
        ErrorMessage("Todos los campos son requeridos");
    }


    //App_HttpHandlers/FormularioAsistenteVirtualHandler.ashx xxx
}


var SetupAsistenteVirtual = function () {
  //Cargar opciones CHAT
  //
  EjecutarPostAjax(
    "/App_HttpHandlers/MobileAppHandler.ashx?accion=getcatalogoasistentevirtual",
    {}
  ).then((response) => {
    _optionChatList = response.data;
    if (window.location.href.includes("chat=open")) {
      ToggleChatBot();
    }
  });

  $(".MenuDerechaContainer  a[href$='preguntas_frecuentes.aspx']").click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    ToggleChatBot();
  });
};
;
var FixLanguageDisplay = function () {
  setTimeout(function () {
    var $optionSpanish = $("option[value='']");
    $("option[value='']").text("Español");
    if ($optionSpanish.length == 0) {
      $(".goog-te-combo").prepend("<option value='es'>Español</option>");
    }
    $("option[value=en]").text("English");
    $("option[value=fr]").text("Français");
    $("option[value=it]").text("Italiano");
    $("option[value=pt]").text("Português");
    $("option[value=de]").text("Deutsch");
    $("option[value=ja]").text("日本");
    $("option[value='zh-CN']").text("中国人");
    if (window.CurrentLanguage !== undefined && window.CurrentLanguage) {
      $(".goog-te-combo").val(window.CurrentLanguage);
    }
  }, 500);
};

function googleTranslateElementInit() {
  window.GTranslate = new google.translate.TranslateElement(
    {
      pageLanguage: "es",
      includedLanguages: "en,fr,pt,it,de,zh-CN,ja",
      /*,layout: google.translate.TranslateElement.InlineLayout.SIMPLE*/
    },
    "google_translate_element"
  );

  $(window).on("load", function () {
    setTimeout(FixLanguageDisplay, 100);
    $(".goog-te-combo").change(function (e) {
      window.CurrentLanguage = $(".goog-te-combo").val();
      FixLanguageDisplay();
    });
  });
}
;
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);            
        }
    });
};
// -----------------------------------
// 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);
	});

});;
/*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);
	});

});;
/*
     _ _      _       _
 ___| (_) ___| | __  (_)___
/ __| | |/ __| |/ /  | / __|
\__ \ | | (__|   < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
                   |__/

 Version: 1.8.1
  Author: Ken Wheeler
 Website: http://kenwheeler.github.io
    Docs: http://kenwheeler.github.io/slick
    Repo: http://github.com/kenwheeler/slick
  Issues: http://github.com/kenwheeler/slick/issues

 */
/* global window, document, define, jQuery, setInterval, clearInterval */
;(function(factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports !== 'undefined') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery);
    }

}(function($) {
    'use strict';
    var Slick = window.Slick || {};

    Slick = (function() {

        var instanceUid = 0;

        function Slick(element, settings) {

            var _ = this, dataSettings;

            _.defaults = {
                accessibility: true,
                adaptiveHeight: false,
                appendArrows: $(element),
                appendDots: $(element),
                arrows: true,
                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: false,
                autoplaySpeed: 3000,
                centerMode: false,
                centerPadding: '50px',
                cssEase: 'ease',
                customPaging: function(slider, i) {
                    return $('<button type="button" />').text(i + 1);
                },
                dots: false,
                dotsClass: 'slick-dots',
                draggable: true,
                easing: 'linear',
                edgeFriction: 0.35,
                fade: false,
                focusOnSelect: false,
                focusOnChange: false,
                infinite: true,
                initialSlide: 0,
                lazyLoad: 'ondemand',
                mobileFirst: false,
                pauseOnHover: true,
                pauseOnFocus: true,
                pauseOnDotsHover: false,
                respondTo: 'window',
                responsive: null,
                rows: 1,
                rtl: false,
                slide: '',
                slidesPerRow: 1,
                slidesToShow: 1,
                slidesToScroll: 1,
                speed: 500,
                swipe: true,
                swipeToSlide: false,
                touchMove: true,
                touchThreshold: 5,
                useCSS: true,
                useTransform: true,
                variableWidth: false,
                vertical: false,
                verticalSwiping: false,
                waitForAnimate: true,
                zIndex: 1000
            };

            _.initials = {
                animating: false,
                dragging: false,
                autoPlayTimer: null,
                currentDirection: 0,
                currentLeft: null,
                currentSlide: 0,
                direction: 1,
                $dots: null,
                listWidth: null,
                listHeight: null,
                loadIndex: 0,
                $nextArrow: null,
                $prevArrow: null,
                scrolling: false,
                slideCount: null,
                slideWidth: null,
                $slideTrack: null,
                $slides: null,
                sliding: false,
                slideOffset: 0,
                swipeLeft: null,
                swiping: false,
                $list: null,
                touchObject: {},
                transformsEnabled: false,
                unslicked: false
            };

            $.extend(_, _.initials);

            _.activeBreakpoint = null;
            _.animType = null;
            _.animProp = null;
            _.breakpoints = [];
            _.breakpointSettings = [];
            _.cssTransitions = false;
            _.focussed = false;
            _.interrupted = false;
            _.hidden = 'hidden';
            _.paused = true;
            _.positionProp = null;
            _.respondTo = null;
            _.rowCount = 1;
            _.shouldClick = true;
            _.$slider = $(element);
            _.$slidesCache = null;
            _.transformType = null;
            _.transitionType = null;
            _.visibilityChange = 'visibilitychange';
            _.windowWidth = 0;
            _.windowTimer = null;

            dataSettings = $(element).data('slick') || {};

            _.options = $.extend({}, _.defaults, settings, dataSettings);

            _.currentSlide = _.options.initialSlide;

            _.originalSettings = _.options;

            if (typeof document.mozHidden !== 'undefined') {
                _.hidden = 'mozHidden';
                _.visibilityChange = 'mozvisibilitychange';
            } else if (typeof document.webkitHidden !== 'undefined') {
                _.hidden = 'webkitHidden';
                _.visibilityChange = 'webkitvisibilitychange';
            }

            _.autoPlay = $.proxy(_.autoPlay, _);
            _.autoPlayClear = $.proxy(_.autoPlayClear, _);
            _.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
            _.changeSlide = $.proxy(_.changeSlide, _);
            _.clickHandler = $.proxy(_.clickHandler, _);
            _.selectHandler = $.proxy(_.selectHandler, _);
            _.setPosition = $.proxy(_.setPosition, _);
            _.swipeHandler = $.proxy(_.swipeHandler, _);
            _.dragHandler = $.proxy(_.dragHandler, _);
            _.keyHandler = $.proxy(_.keyHandler, _);

            _.instanceUid = instanceUid++;

            // A simple way to check for HTML strings
            // Strict HTML recognition (must start with <)
            // Extracted from jQuery v1.11 source
            _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;


            _.registerBreakpoints();
            _.init(true);

        }

        return Slick;

    }());

    Slick.prototype.activateADA = function() {
        var _ = this;

        _.$slideTrack.find('.slick-active').attr({
            'aria-hidden': 'false'
        }).find('a, input, button, select').attr({
            'tabindex': '0'
        });

    };

    Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            addBefore = index;
            index = null;
        } else if (index < 0 || (index >= _.slideCount)) {
            return false;
        }

        _.unload();

        if (typeof(index) === 'number') {
            if (index === 0 && _.$slides.length === 0) {
                $(markup).appendTo(_.$slideTrack);
            } else if (addBefore) {
                $(markup).insertBefore(_.$slides.eq(index));
            } else {
                $(markup).insertAfter(_.$slides.eq(index));
            }
        } else {
            if (addBefore === true) {
                $(markup).prependTo(_.$slideTrack);
            } else {
                $(markup).appendTo(_.$slideTrack);
            }
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slides.each(function(index, element) {
            $(element).attr('data-slick-index', index);
        });

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.animateHeight = function() {
        var _ = this;
        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.animate({
                height: targetHeight
            }, _.options.speed);
        }
    };

    Slick.prototype.animateSlide = function(targetLeft, callback) {

        var animProps = {},
            _ = this;

        _.animateHeight();

        if (_.options.rtl === true && _.options.vertical === false) {
            targetLeft = -targetLeft;
        }
        if (_.transformsEnabled === false) {
            if (_.options.vertical === false) {
                _.$slideTrack.animate({
                    left: targetLeft
                }, _.options.speed, _.options.easing, callback);
            } else {
                _.$slideTrack.animate({
                    top: targetLeft
                }, _.options.speed, _.options.easing, callback);
            }

        } else {

            if (_.cssTransitions === false) {
                if (_.options.rtl === true) {
                    _.currentLeft = -(_.currentLeft);
                }
                $({
                    animStart: _.currentLeft
                }).animate({
                    animStart: targetLeft
                }, {
                    duration: _.options.speed,
                    easing: _.options.easing,
                    step: function(now) {
                        now = Math.ceil(now);
                        if (_.options.vertical === false) {
                            animProps[_.animType] = 'translate(' +
                                now + 'px, 0px)';
                            _.$slideTrack.css(animProps);
                        } else {
                            animProps[_.animType] = 'translate(0px,' +
                                now + 'px)';
                            _.$slideTrack.css(animProps);
                        }
                    },
                    complete: function() {
                        if (callback) {
                            callback.call();
                        }
                    }
                });

            } else {

                _.applyTransition();
                targetLeft = Math.ceil(targetLeft);

                if (_.options.vertical === false) {
                    animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
                } else {
                    animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
                }
                _.$slideTrack.css(animProps);

                if (callback) {
                    setTimeout(function() {

                        _.disableTransition();

                        callback.call();
                    }, _.options.speed);
                }

            }

        }

    };

    Slick.prototype.getNavTarget = function() {

        var _ = this,
            asNavFor = _.options.asNavFor;

        if ( asNavFor && asNavFor !== null ) {
            asNavFor = $(asNavFor).not(_.$slider);
        }

        return asNavFor;

    };

    Slick.prototype.asNavFor = function(index) {

        var _ = this,
            asNavFor = _.getNavTarget();

        if ( asNavFor !== null && typeof asNavFor === 'object' ) {
            asNavFor.each(function() {
                var target = $(this).slick('getSlick');
                if(!target.unslicked) {
                    target.slideHandler(index, true);
                }
            });
        }

    };

    Slick.prototype.applyTransition = function(slide) {

        var _ = this,
            transition = {};

        if (_.options.fade === false) {
            transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
        } else {
            transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
        }

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.autoPlay = function() {

        var _ = this;

        _.autoPlayClear();

        if ( _.slideCount > _.options.slidesToShow ) {
            _.autoPlayTimer = setInterval( _.autoPlayIterator, _.options.autoplaySpeed );
        }

    };

    Slick.prototype.autoPlayClear = function() {

        var _ = this;

        if (_.autoPlayTimer) {
            clearInterval(_.autoPlayTimer);
        }

    };

    Slick.prototype.autoPlayIterator = function() {

        var _ = this,
            slideTo = _.currentSlide + _.options.slidesToScroll;

        if ( !_.paused && !_.interrupted && !_.focussed ) {

            if ( _.options.infinite === false ) {

                if ( _.direction === 1 && ( _.currentSlide + 1 ) === ( _.slideCount - 1 )) {
                    _.direction = 0;
                }

                else if ( _.direction === 0 ) {

                    slideTo = _.currentSlide - _.options.slidesToScroll;

                    if ( _.currentSlide - 1 === 0 ) {
                        _.direction = 1;
                    }

                }

            }

            _.slideHandler( slideTo );

        }

    };

    Slick.prototype.buildArrows = function() {

        var _ = this;

        if (_.options.arrows === true ) {

            _.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
            _.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');

            if( _.slideCount > _.options.slidesToShow ) {

                _.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
                _.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');

                if (_.htmlExpr.test(_.options.prevArrow)) {
                    _.$prevArrow.prependTo(_.options.appendArrows);
                }

                if (_.htmlExpr.test(_.options.nextArrow)) {
                    _.$nextArrow.appendTo(_.options.appendArrows);
                }

                if (_.options.infinite !== true) {
                    _.$prevArrow
                        .addClass('slick-disabled')
                        .attr('aria-disabled', 'true');
                }

            } else {

                _.$prevArrow.add( _.$nextArrow )

                    .addClass('slick-hidden')
                    .attr({
                        'aria-disabled': 'true',
                        'tabindex': '-1'
                    });

            }

        }

    };

    Slick.prototype.buildDots = function() {

        var _ = this,
            i, dot;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$slider.addClass('slick-dotted');

            dot = $('<ul />').addClass(_.options.dotsClass);

            for (i = 0; i <= _.getDotCount(); i += 1) {
                dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
            }

            _.$dots = dot.appendTo(_.options.appendDots);

            _.$dots.find('li').first().addClass('slick-active');

        }

    };

    Slick.prototype.buildOut = function() {

        var _ = this;

        _.$slides =
            _.$slider
                .children( _.options.slide + ':not(.slick-cloned)')
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        _.$slides.each(function(index, element) {
            $(element)
                .attr('data-slick-index', index)
                .data('originalStyling', $(element).attr('style') || '');
        });

        _.$slider.addClass('slick-slider');

        _.$slideTrack = (_.slideCount === 0) ?
            $('<div class="slick-track"/>').appendTo(_.$slider) :
            _.$slides.wrapAll('<div class="slick-track"/>').parent();

        _.$list = _.$slideTrack.wrap(
            '<div class="slick-list"/>').parent();
        _.$slideTrack.css('opacity', 0);

        if (_.options.centerMode === true || _.options.swipeToSlide === true) {
            _.options.slidesToScroll = 1;
        }

        $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');

        _.setupInfinite();

        _.buildArrows();

        _.buildDots();

        _.updateDots();


        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        if (_.options.draggable === true) {
            _.$list.addClass('draggable');
        }

    };

    Slick.prototype.buildRows = function() {

        var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection;

        newSlides = document.createDocumentFragment();
        originalSlides = _.$slider.children();

        if(_.options.rows > 0) {

            slidesPerSection = _.options.slidesPerRow * _.options.rows;
            numOfSlides = Math.ceil(
                originalSlides.length / slidesPerSection
            );

            for(a = 0; a < numOfSlides; a++){
                var slide = document.createElement('div');
                for(b = 0; b < _.options.rows; b++) {
                    var row = document.createElement('div');
                    for(c = 0; c < _.options.slidesPerRow; c++) {
                        var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c));
                        if (originalSlides.get(target)) {
                            row.appendChild(originalSlides.get(target));
                        }
                    }
                    slide.appendChild(row);
                }
                newSlides.appendChild(slide);
            }

            _.$slider.empty().append(newSlides);
            _.$slider.children().children().children()
                .css({
                    'width':(100 / _.options.slidesPerRow) + '%',
                    'display': 'inline-block'
                });

        }

    };

    Slick.prototype.checkResponsive = function(initial, forceUpdate) {

        var _ = this,
            breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false;
        var sliderWidth = _.$slider.width();
        var windowWidth = window.innerWidth || $(window).width();

        if (_.respondTo === 'window') {
            respondToWidth = windowWidth;
        } else if (_.respondTo === 'slider') {
            respondToWidth = sliderWidth;
        } else if (_.respondTo === 'min') {
            respondToWidth = Math.min(windowWidth, sliderWidth);
        }

        if ( _.options.responsive &&
            _.options.responsive.length &&
            _.options.responsive !== null) {

            targetBreakpoint = null;

            for (breakpoint in _.breakpoints) {
                if (_.breakpoints.hasOwnProperty(breakpoint)) {
                    if (_.originalSettings.mobileFirst === false) {
                        if (respondToWidth < _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    } else {
                        if (respondToWidth > _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    }
                }
            }

            if (targetBreakpoint !== null) {
                if (_.activeBreakpoint !== null) {
                    if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
                        _.activeBreakpoint =
                            targetBreakpoint;
                        if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                            _.unslick(targetBreakpoint);
                        } else {
                            _.options = $.extend({}, _.originalSettings,
                                _.breakpointSettings[
                                    targetBreakpoint]);
                            if (initial === true) {
                                _.currentSlide = _.options.initialSlide;
                            }
                            _.refresh(initial);
                        }
                        triggerBreakpoint = targetBreakpoint;
                    }
                } else {
                    _.activeBreakpoint = targetBreakpoint;
                    if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                        _.unslick(targetBreakpoint);
                    } else {
                        _.options = $.extend({}, _.originalSettings,
                            _.breakpointSettings[
                                targetBreakpoint]);
                        if (initial === true) {
                            _.currentSlide = _.options.initialSlide;
                        }
                        _.refresh(initial);
                    }
                    triggerBreakpoint = targetBreakpoint;
                }
            } else {
                if (_.activeBreakpoint !== null) {
                    _.activeBreakpoint = null;
                    _.options = _.originalSettings;
                    if (initial === true) {
                        _.currentSlide = _.options.initialSlide;
                    }
                    _.refresh(initial);
                    triggerBreakpoint = targetBreakpoint;
                }
            }

            // only trigger breakpoints during an actual break. not on initialize.
            if( !initial && triggerBreakpoint !== false ) {
                _.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
            }
        }

    };

    Slick.prototype.changeSlide = function(event, dontAnimate) {

        var _ = this,
            $target = $(event.currentTarget),
            indexOffset, slideOffset, unevenOffset;

        // If target is a link, prevent default action.
        if($target.is('a')) {
            event.preventDefault();
        }

        // If target is not the <li> element (ie: a child), find the <li>.
        if(!$target.is('li')) {
            $target = $target.closest('li');
        }

        unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0);
        indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;

        switch (event.data.message) {

            case 'previous':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
                }
                break;

            case 'next':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
                }
                break;

            case 'index':
                var index = event.data.index === 0 ? 0 :
                    event.data.index || $target.index() * _.options.slidesToScroll;

                _.slideHandler(_.checkNavigable(index), false, dontAnimate);
                $target.children().trigger('focus');
                break;

            default:
                return;
        }

    };

    Slick.prototype.checkNavigable = function(index) {

        var _ = this,
            navigables, prevNavigable;

        navigables = _.getNavigableIndexes();
        prevNavigable = 0;
        if (index > navigables[navigables.length - 1]) {
            index = navigables[navigables.length - 1];
        } else {
            for (var n in navigables) {
                if (index < navigables[n]) {
                    index = prevNavigable;
                    break;
                }
                prevNavigable = navigables[n];
            }
        }

        return index;
    };

    Slick.prototype.cleanUpEvents = function() {

        var _ = this;

        if (_.options.dots && _.$dots !== null) {

            $('li', _.$dots)
                .off('click.slick', _.changeSlide)
                .off('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .off('mouseleave.slick', $.proxy(_.interrupt, _, false));

            if (_.options.accessibility === true) {
                _.$dots.off('keydown.slick', _.keyHandler);
            }
        }

        _.$slider.off('focus.slick blur.slick');

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
            _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);

            if (_.options.accessibility === true) {
                _.$prevArrow && _.$prevArrow.off('keydown.slick', _.keyHandler);
                _.$nextArrow && _.$nextArrow.off('keydown.slick', _.keyHandler);
            }
        }

        _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
        _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
        _.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
        _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);

        _.$list.off('click.slick', _.clickHandler);

        $(document).off(_.visibilityChange, _.visibility);

        _.cleanUpSlideEvents();

        if (_.options.accessibility === true) {
            _.$list.off('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().off('click.slick', _.selectHandler);
        }

        $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);

        $(window).off('resize.slick.slick-' + _.instanceUid, _.resize);

        $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);

        $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);

    };

    Slick.prototype.cleanUpSlideEvents = function() {

        var _ = this;

        _.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
        _.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));

    };

    Slick.prototype.cleanUpRows = function() {

        var _ = this, originalSlides;

        if(_.options.rows > 0) {
            originalSlides = _.$slides.children().children();
            originalSlides.removeAttr('style');
            _.$slider.empty().append(originalSlides);
        }

    };

    Slick.prototype.clickHandler = function(event) {

        var _ = this;

        if (_.shouldClick === false) {
            event.stopImmediatePropagation();
            event.stopPropagation();
            event.preventDefault();
        }

    };

    Slick.prototype.destroy = function(refresh) {

        var _ = this;

        _.autoPlayClear();

        _.touchObject = {};

        _.cleanUpEvents();

        $('.slick-cloned', _.$slider).detach();

        if (_.$dots) {
            _.$dots.remove();
        }

        if ( _.$prevArrow && _.$prevArrow.length ) {

            _.$prevArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.prevArrow )) {
                _.$prevArrow.remove();
            }
        }

        if ( _.$nextArrow && _.$nextArrow.length ) {

            _.$nextArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.nextArrow )) {
                _.$nextArrow.remove();
            }
        }


        if (_.$slides) {

            _.$slides
                .removeClass('slick-slide slick-active slick-center slick-visible slick-current')
                .removeAttr('aria-hidden')
                .removeAttr('data-slick-index')
                .each(function(){
                    $(this).attr('style', $(this).data('originalStyling'));
                });

            _.$slideTrack.children(this.options.slide).detach();

            _.$slideTrack.detach();

            _.$list.detach();

            _.$slider.append(_.$slides);
        }

        _.cleanUpRows();

        _.$slider.removeClass('slick-slider');
        _.$slider.removeClass('slick-initialized');
        _.$slider.removeClass('slick-dotted');

        _.unslicked = true;

        if(!refresh) {
            _.$slider.trigger('destroy', [_]);
        }

    };

    Slick.prototype.disableTransition = function(slide) {

        var _ = this,
            transition = {};

        transition[_.transitionType] = '';

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.fadeSlide = function(slideIndex, callback) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).css({
                zIndex: _.options.zIndex
            });

            _.$slides.eq(slideIndex).animate({
                opacity: 1
            }, _.options.speed, _.options.easing, callback);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 1,
                zIndex: _.options.zIndex
            });

            if (callback) {
                setTimeout(function() {

                    _.disableTransition(slideIndex);

                    callback.call();
                }, _.options.speed);
            }

        }

    };

    Slick.prototype.fadeSlideOut = function(slideIndex) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).animate({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            }, _.options.speed, _.options.easing);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            });

        }

    };

    Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) {

        var _ = this;

        if (filter !== null) {

            _.$slidesCache = _.$slides;

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.filter(filter).appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.focusHandler = function() {

        var _ = this;

        // If any child element receives focus within the slider we need to pause the autoplay
        _.$slider
            .off('focus.slick blur.slick')
            .on(
                'focus.slick',
                '*', 
                function(event) {
                    var $sf = $(this);

                    setTimeout(function() {
                        if( _.options.pauseOnFocus ) {
                            if ($sf.is(':focus')) {
                                _.focussed = true;
                                _.autoPlay();
                            }
                        }
                    }, 0);
                }
            ).on(
                'blur.slick',
                '*', 
                function(event) {
                    var $sf = $(this);

                    // When a blur occurs on any elements within the slider we become unfocused
                    if( _.options.pauseOnFocus ) {
                        _.focussed = false;
                        _.autoPlay();
                    }
                }
            );
    };

    Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() {

        var _ = this;
        return _.currentSlide;

    };

    Slick.prototype.getDotCount = function() {

        var _ = this;

        var breakPoint = 0;
        var counter = 0;
        var pagerQty = 0;

        if (_.options.infinite === true) {
            if (_.slideCount <= _.options.slidesToShow) {
                 ++pagerQty;
            } else {
                while (breakPoint < _.slideCount) {
                    ++pagerQty;
                    breakPoint = counter + _.options.slidesToScroll;
                    counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
                }
            }
        } else if (_.options.centerMode === true) {
            pagerQty = _.slideCount;
        } else if(!_.options.asNavFor) {
            pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
        }else {
            while (breakPoint < _.slideCount) {
                ++pagerQty;
                breakPoint = counter + _.options.slidesToScroll;
                counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
            }
        }

        return pagerQty - 1;

    };

    Slick.prototype.getLeft = function(slideIndex) {

        var _ = this,
            targetLeft,
            verticalHeight,
            verticalOffset = 0,
            targetSlide,
            coef;

        _.slideOffset = 0;
        verticalHeight = _.$slides.first().outerHeight(true);

        if (_.options.infinite === true) {
            if (_.slideCount > _.options.slidesToShow) {
                _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1;
                coef = -1

                if (_.options.vertical === true && _.options.centerMode === true) {
                    if (_.options.slidesToShow === 2) {
                        coef = -1.5;
                    } else if (_.options.slidesToShow === 1) {
                        coef = -2
                    }
                }
                verticalOffset = (verticalHeight * _.options.slidesToShow) * coef;
            }
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
                    if (slideIndex > _.slideCount) {
                        _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1;
                        verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1;
                    } else {
                        _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1;
                        verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1;
                    }
                }
            }
        } else {
            if (slideIndex + _.options.slidesToShow > _.slideCount) {
                _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth;
                verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight;
            }
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.slideOffset = 0;
            verticalOffset = 0;
        }

        if (_.options.centerMode === true && _.slideCount <= _.options.slidesToShow) {
            _.slideOffset = ((_.slideWidth * Math.floor(_.options.slidesToShow)) / 2) - ((_.slideWidth * _.slideCount) / 2);
        } else if (_.options.centerMode === true && _.options.infinite === true) {
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
        } else if (_.options.centerMode === true) {
            _.slideOffset = 0;
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
        }

        if (_.options.vertical === false) {
            targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset;
        } else {
            targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset;
        }

        if (_.options.variableWidth === true) {

            if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
            } else {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
            }

            if (_.options.rtl === true) {
                if (targetSlide[0]) {
                    targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                } else {
                    targetLeft =  0;
                }
            } else {
                targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
            }

            if (_.options.centerMode === true) {
                if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
                } else {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
                }

                if (_.options.rtl === true) {
                    if (targetSlide[0]) {
                        targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                    } else {
                        targetLeft =  0;
                    }
                } else {
                    targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
                }

                targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
            }
        }

        return targetLeft;

    };

    Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) {

        var _ = this;

        return _.options[option];

    };

    Slick.prototype.getNavigableIndexes = function() {

        var _ = this,
            breakPoint = 0,
            counter = 0,
            indexes = [],
            max;

        if (_.options.infinite === false) {
            max = _.slideCount;
        } else {
            breakPoint = _.options.slidesToScroll * -1;
            counter = _.options.slidesToScroll * -1;
            max = _.slideCount * 2;
        }

        while (breakPoint < max) {
            indexes.push(breakPoint);
            breakPoint = counter + _.options.slidesToScroll;
            counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
        }

        return indexes;

    };

    Slick.prototype.getSlick = function() {

        return this;

    };

    Slick.prototype.getSlideCount = function() {

        var _ = this,
            slidesTraversed, swipedSlide, swipeTarget, centerOffset;

        centerOffset = _.options.centerMode === true ? Math.floor(_.$list.width() / 2) : 0;
        swipeTarget = (_.swipeLeft * -1) + centerOffset;

        if (_.options.swipeToSlide === true) {

            _.$slideTrack.find('.slick-slide').each(function(index, slide) {

                var slideOuterWidth, slideOffset, slideRightBoundary;
                slideOuterWidth = $(slide).outerWidth();
                slideOffset = slide.offsetLeft;
                if (_.options.centerMode !== true) {
                    slideOffset += (slideOuterWidth / 2);
                }

                slideRightBoundary = slideOffset + (slideOuterWidth);

                if (swipeTarget < slideRightBoundary) {
                    swipedSlide = slide;
                    return false;
                }
            });

            slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;

            return slidesTraversed;

        } else {
            return _.options.slidesToScroll;
        }

    };

    Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'index',
                index: parseInt(slide)
            }
        }, dontAnimate);

    };

    Slick.prototype.init = function(creation) {

        var _ = this;

        if (!$(_.$slider).hasClass('slick-initialized')) {

            $(_.$slider).addClass('slick-initialized');

            _.buildRows();
            _.buildOut();
            _.setProps();
            _.startLoad();
            _.loadSlider();
            _.initializeEvents();
            _.updateArrows();
            _.updateDots();
            _.checkResponsive(true);
            _.focusHandler();

        }

        if (creation) {
            _.$slider.trigger('init', [_]);
        }

        if (_.options.accessibility === true) {
            _.initADA();
        }

        if ( _.options.autoplay ) {

            _.paused = false;
            _.autoPlay();

        }

    };

    Slick.prototype.initADA = function() {
        var _ = this,
                numDotGroups = Math.ceil(_.slideCount / _.options.slidesToScroll),
                tabControlIndexes = _.getNavigableIndexes().filter(function(val) {
                    return (val >= 0) && (val < _.slideCount);
                });

        _.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
            'aria-hidden': 'true',
            'tabindex': '-1'
        }).find('a, input, button, select').attr({
            'tabindex': '-1'
        });

        if (_.$dots !== null) {
            _.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) {
                var slideControlIndex = tabControlIndexes.indexOf(i);

                $(this).attr({
                    'role': 'tabpanel',
                    'id': 'slick-slide' + _.instanceUid + i,
                    'tabindex': -1
                });

                if (slideControlIndex !== -1) {
                   var ariaButtonControl = 'slick-slide-control' + _.instanceUid + slideControlIndex
                   if ($('#' + ariaButtonControl).length) {
                     $(this).attr({
                         'aria-describedby': ariaButtonControl
                     });
                   }
                }
            });

            _.$dots.attr('role', 'tablist').find('li').each(function(i) {
                var mappedSlideIndex = tabControlIndexes[i];

                $(this).attr({
                    'role': 'presentation'
                });

                $(this).find('button').first().attr({
                    'role': 'tab',
                    'id': 'slick-slide-control' + _.instanceUid + i,
                    'aria-controls': 'slick-slide' + _.instanceUid + mappedSlideIndex,
                    'aria-label': (i + 1) + ' of ' + numDotGroups,
                    'aria-selected': null,
                    'tabindex': '-1'
                });

            }).eq(_.currentSlide).find('button').attr({
                'aria-selected': 'true',
                'tabindex': '0'
            }).end();
        }

        for (var i=_.currentSlide, max=i+_.options.slidesToShow; i < max; i++) {
          if (_.options.focusOnChange) {
            _.$slides.eq(i).attr({'tabindex': '0'});
          } else {
            _.$slides.eq(i).removeAttr('tabindex');
          }
        }

        _.activateADA();

    };

    Slick.prototype.initArrowEvents = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'previous'
               }, _.changeSlide);
            _.$nextArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'next'
               }, _.changeSlide);

            if (_.options.accessibility === true) {
                _.$prevArrow.on('keydown.slick', _.keyHandler);
                _.$nextArrow.on('keydown.slick', _.keyHandler);
            }
        }

    };

    Slick.prototype.initDotEvents = function() {

        var _ = this;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
            $('li', _.$dots).on('click.slick', {
                message: 'index'
            }, _.changeSlide);

            if (_.options.accessibility === true) {
                _.$dots.on('keydown.slick', _.keyHandler);
            }
        }

        if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.slideCount > _.options.slidesToShow) {

            $('li', _.$dots)
                .on('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initSlideEvents = function() {

        var _ = this;

        if ( _.options.pauseOnHover ) {

            _.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
            _.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initializeEvents = function() {

        var _ = this;

        _.initArrowEvents();

        _.initDotEvents();
        _.initSlideEvents();

        _.$list.on('touchstart.slick mousedown.slick', {
            action: 'start'
        }, _.swipeHandler);
        _.$list.on('touchmove.slick mousemove.slick', {
            action: 'move'
        }, _.swipeHandler);
        _.$list.on('touchend.slick mouseup.slick', {
            action: 'end'
        }, _.swipeHandler);
        _.$list.on('touchcancel.slick mouseleave.slick', {
            action: 'end'
        }, _.swipeHandler);

        _.$list.on('click.slick', _.clickHandler);

        $(document).on(_.visibilityChange, $.proxy(_.visibility, _));

        if (_.options.accessibility === true) {
            _.$list.on('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        $(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));

        $(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));

        $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);

        $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
        $(_.setPosition);

    };

    Slick.prototype.initUI = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.show();
            _.$nextArrow.show();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.show();

        }

    };

    Slick.prototype.keyHandler = function(event) {

        var _ = this;
         //Dont slide if the cursor is inside the form fields and arrow keys are pressed
        if(!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
            if (event.keyCode === 37 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'next' :  'previous'
                    }
                });
            } else if (event.keyCode === 39 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'previous' : 'next'
                    }
                });
            }
        }

    };

    Slick.prototype.lazyLoad = function() {

        var _ = this,
            loadRange, cloneRange, rangeStart, rangeEnd;

        function loadImages(imagesScope) {

            $('img[data-lazy]', imagesScope).each(function() {

                var image = $(this),
                    imageSource = $(this).attr('data-lazy'),
                    imageSrcSet = $(this).attr('data-srcset'),
                    imageSizes  = $(this).attr('data-sizes') || _.$slider.attr('data-sizes'),
                    imageToLoad = document.createElement('img');

                imageToLoad.onload = function() {

                    image
                        .animate({ opacity: 0 }, 100, function() {

                            if (imageSrcSet) {
                                image
                                    .attr('srcset', imageSrcSet );

                                if (imageSizes) {
                                    image
                                        .attr('sizes', imageSizes );
                                }
                            }

                            image
                                .attr('src', imageSource)
                                .animate({ opacity: 1 }, 200, function() {
                                    image
                                        .removeAttr('data-lazy data-srcset data-sizes')
                                        .removeClass('slick-loading');
                                });
                            _.$slider.trigger('lazyLoaded', [_, image, imageSource]);
                        });

                };

                imageToLoad.onerror = function() {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                };

                imageToLoad.src = imageSource;

            });

        }

        if (_.options.centerMode === true) {
            if (_.options.infinite === true) {
                rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
                rangeEnd = rangeStart + _.options.slidesToShow + 2;
            } else {
                rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
                rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
            }
        } else {
            rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
            rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
            if (_.options.fade === true) {
                if (rangeStart > 0) rangeStart--;
                if (rangeEnd <= _.slideCount) rangeEnd++;
            }
        }

        loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);

        if (_.options.lazyLoad === 'anticipated') {
            var prevSlide = rangeStart - 1,
                nextSlide = rangeEnd,
                $slides = _.$slider.find('.slick-slide');

            for (var i = 0; i < _.options.slidesToScroll; i++) {
                if (prevSlide < 0) prevSlide = _.slideCount - 1;
                loadRange = loadRange.add($slides.eq(prevSlide));
                loadRange = loadRange.add($slides.eq(nextSlide));
                prevSlide--;
                nextSlide++;
            }
        }

        loadImages(loadRange);

        if (_.slideCount <= _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-slide');
            loadImages(cloneRange);
        } else
        if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
            loadImages(cloneRange);
        } else if (_.currentSlide === 0) {
            cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
            loadImages(cloneRange);
        }

    };

    Slick.prototype.loadSlider = function() {

        var _ = this;

        _.setPosition();

        _.$slideTrack.css({
            opacity: 1
        });

        _.$slider.removeClass('slick-loading');

        _.initUI();

        if (_.options.lazyLoad === 'progressive') {
            _.progressiveLazyLoad();
        }

    };

    Slick.prototype.next = Slick.prototype.slickNext = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'next'
            }
        });

    };

    Slick.prototype.orientationChange = function() {

        var _ = this;

        _.checkResponsive();
        _.setPosition();

    };

    Slick.prototype.pause = Slick.prototype.slickPause = function() {

        var _ = this;

        _.autoPlayClear();
        _.paused = true;

    };

    Slick.prototype.play = Slick.prototype.slickPlay = function() {

        var _ = this;

        _.autoPlay();
        _.options.autoplay = true;
        _.paused = false;
        _.focussed = false;
        _.interrupted = false;

    };

    Slick.prototype.postSlide = function(index) {

        var _ = this;

        if( !_.unslicked ) {

            _.$slider.trigger('afterChange', [_, index]);

            _.animating = false;

            if (_.slideCount > _.options.slidesToShow) {
                _.setPosition();
            }

            _.swipeLeft = null;

            if ( _.options.autoplay ) {
                _.autoPlay();
            }

            if (_.options.accessibility === true) {
                _.initADA();

                if (_.options.focusOnChange) {
                    var $currentSlide = $(_.$slides.get(_.currentSlide));
                    $currentSlide.attr('tabindex', 0).focus();
                }
            }

        }

    };

    Slick.prototype.prev = Slick.prototype.slickPrev = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'previous'
            }
        });

    };

    Slick.prototype.preventDefault = function(event) {

        event.preventDefault();

    };

    Slick.prototype.progressiveLazyLoad = function( tryCount ) {

        tryCount = tryCount || 1;

        var _ = this,
            $imgsToLoad = $( 'img[data-lazy]', _.$slider ),
            image,
            imageSource,
            imageSrcSet,
            imageSizes,
            imageToLoad;

        if ( $imgsToLoad.length ) {

            image = $imgsToLoad.first();
            imageSource = image.attr('data-lazy');
            imageSrcSet = image.attr('data-srcset');
            imageSizes  = image.attr('data-sizes') || _.$slider.attr('data-sizes');
            imageToLoad = document.createElement('img');

            imageToLoad.onload = function() {

                if (imageSrcSet) {
                    image
                        .attr('srcset', imageSrcSet );

                    if (imageSizes) {
                        image
                            .attr('sizes', imageSizes );
                    }
                }

                image
                    .attr( 'src', imageSource )
                    .removeAttr('data-lazy data-srcset data-sizes')
                    .removeClass('slick-loading');

                if ( _.options.adaptiveHeight === true ) {
                    _.setPosition();
                }

                _.$slider.trigger('lazyLoaded', [ _, image, imageSource ]);
                _.progressiveLazyLoad();

            };

            imageToLoad.onerror = function() {

                if ( tryCount < 3 ) {

                    /**
                     * try to load the image 3 times,
                     * leave a slight delay so we don't get
                     * servers blocking the request.
                     */
                    setTimeout( function() {
                        _.progressiveLazyLoad( tryCount + 1 );
                    }, 500 );

                } else {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                    _.progressiveLazyLoad();

                }

            };

            imageToLoad.src = imageSource;

        } else {

            _.$slider.trigger('allImagesLoaded', [ _ ]);

        }

    };

    Slick.prototype.refresh = function( initializing ) {

        var _ = this, currentSlide, lastVisibleIndex;

        lastVisibleIndex = _.slideCount - _.options.slidesToShow;

        // in non-infinite sliders, we don't want to go past the
        // last visible index.
        if( !_.options.infinite && ( _.currentSlide > lastVisibleIndex )) {
            _.currentSlide = lastVisibleIndex;
        }

        // if less slides than to show, go to start.
        if ( _.slideCount <= _.options.slidesToShow ) {
            _.currentSlide = 0;

        }

        currentSlide = _.currentSlide;

        _.destroy(true);

        $.extend(_, _.initials, { currentSlide: currentSlide });

        _.init();

        if( !initializing ) {

            _.changeSlide({
                data: {
                    message: 'index',
                    index: currentSlide
                }
            }, false);

        }

    };

    Slick.prototype.registerBreakpoints = function() {

        var _ = this, breakpoint, currentBreakpoint, l,
            responsiveSettings = _.options.responsive || null;

        if ( $.type(responsiveSettings) === 'array' && responsiveSettings.length ) {

            _.respondTo = _.options.respondTo || 'window';

            for ( breakpoint in responsiveSettings ) {

                l = _.breakpoints.length-1;

                if (responsiveSettings.hasOwnProperty(breakpoint)) {
                    currentBreakpoint = responsiveSettings[breakpoint].breakpoint;

                    // loop through the breakpoints and cut out any existing
                    // ones with the same breakpoint number, we don't want dupes.
                    while( l >= 0 ) {
                        if( _.breakpoints[l] && _.breakpoints[l] === currentBreakpoint ) {
                            _.breakpoints.splice(l,1);
                        }
                        l--;
                    }

                    _.breakpoints.push(currentBreakpoint);
                    _.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;

                }

            }

            _.breakpoints.sort(function(a, b) {
                return ( _.options.mobileFirst ) ? a-b : b-a;
            });

        }

    };

    Slick.prototype.reinit = function() {

        var _ = this;

        _.$slides =
            _.$slideTrack
                .children(_.options.slide)
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
            _.currentSlide = _.currentSlide - _.options.slidesToScroll;
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.currentSlide = 0;
        }

        _.registerBreakpoints();

        _.setProps();
        _.setupInfinite();
        _.buildArrows();
        _.updateArrows();
        _.initArrowEvents();
        _.buildDots();
        _.updateDots();
        _.initDotEvents();
        _.cleanUpSlideEvents();
        _.initSlideEvents();

        _.checkResponsive(false, true);

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        _.setPosition();
        _.focusHandler();

        _.paused = !_.options.autoplay;
        _.autoPlay();

        _.$slider.trigger('reInit', [_]);

    };

    Slick.prototype.resize = function() {

        var _ = this;

        if ($(window).width() !== _.windowWidth) {
            clearTimeout(_.windowDelay);
            _.windowDelay = window.setTimeout(function() {
                _.windowWidth = $(window).width();
                _.checkResponsive();
                if( !_.unslicked ) { _.setPosition(); }
            }, 50);
        }
    };

    Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            removeBefore = index;
            index = removeBefore === true ? 0 : _.slideCount - 1;
        } else {
            index = removeBefore === true ? --index : index;
        }

        if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
            return false;
        }

        _.unload();

        if (removeAll === true) {
            _.$slideTrack.children().remove();
        } else {
            _.$slideTrack.children(this.options.slide).eq(index).remove();
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.setCSS = function(position) {

        var _ = this,
            positionProps = {},
            x, y;

        if (_.options.rtl === true) {
            position = -position;
        }
        x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
        y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';

        positionProps[_.positionProp] = position;

        if (_.transformsEnabled === false) {
            _.$slideTrack.css(positionProps);
        } else {
            positionProps = {};
            if (_.cssTransitions === false) {
                positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
                _.$slideTrack.css(positionProps);
            } else {
                positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
                _.$slideTrack.css(positionProps);
            }
        }

    };

    Slick.prototype.setDimensions = function() {

        var _ = this;

        if (_.options.vertical === false) {
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: ('0px ' + _.options.centerPadding)
                });
            }
        } else {
            _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: (_.options.centerPadding + ' 0px')
                });
            }
        }

        _.listWidth = _.$list.width();
        _.listHeight = _.$list.height();


        if (_.options.vertical === false && _.options.variableWidth === false) {
            _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
            _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length)));

        } else if (_.options.variableWidth === true) {
            _.$slideTrack.width(5000 * _.slideCount);
        } else {
            _.slideWidth = Math.ceil(_.listWidth);
            _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length)));
        }

        var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
        if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);

    };

    Slick.prototype.setFade = function() {

        var _ = this,
            targetLeft;

        _.$slides.each(function(index, element) {
            targetLeft = (_.slideWidth * index) * -1;
            if (_.options.rtl === true) {
                $(element).css({
                    position: 'relative',
                    right: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            } else {
                $(element).css({
                    position: 'relative',
                    left: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            }
        });

        _.$slides.eq(_.currentSlide).css({
            zIndex: _.options.zIndex - 1,
            opacity: 1
        });

    };

    Slick.prototype.setHeight = function() {

        var _ = this;

        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.css('height', targetHeight);
        }

    };

    Slick.prototype.setOption =
    Slick.prototype.slickSetOption = function() {

        /**
         * accepts arguments in format of:
         *
         *  - for changing a single option's value:
         *     .slick("setOption", option, value, refresh )
         *
         *  - for changing a set of responsive options:
         *     .slick("setOption", 'responsive', [{}, ...], refresh )
         *
         *  - for updating multiple values at once (not responsive)
         *     .slick("setOption", { 'option': value, ... }, refresh )
         */

        var _ = this, l, item, option, value, refresh = false, type;

        if( $.type( arguments[0] ) === 'object' ) {

            option =  arguments[0];
            refresh = arguments[1];
            type = 'multiple';

        } else if ( $.type( arguments[0] ) === 'string' ) {

            option =  arguments[0];
            value = arguments[1];
            refresh = arguments[2];

            if ( arguments[0] === 'responsive' && $.type( arguments[1] ) === 'array' ) {

                type = 'responsive';

            } else if ( typeof arguments[1] !== 'undefined' ) {

                type = 'single';

            }

        }

        if ( type === 'single' ) {

            _.options[option] = value;


        } else if ( type === 'multiple' ) {

            $.each( option , function( opt, val ) {

                _.options[opt] = val;

            });


        } else if ( type === 'responsive' ) {

            for ( item in value ) {

                if( $.type( _.options.responsive ) !== 'array' ) {

                    _.options.responsive = [ value[item] ];

                } else {

                    l = _.options.responsive.length-1;

                    // loop through the responsive object and splice out duplicates.
                    while( l >= 0 ) {

                        if( _.options.responsive[l].breakpoint === value[item].breakpoint ) {

                            _.options.responsive.splice(l,1);

                        }

                        l--;

                    }

                    _.options.responsive.push( value[item] );

                }

            }

        }

        if ( refresh ) {

            _.unload();
            _.reinit();

        }

    };

    Slick.prototype.setPosition = function() {

        var _ = this;

        _.setDimensions();

        _.setHeight();

        if (_.options.fade === false) {
            _.setCSS(_.getLeft(_.currentSlide));
        } else {
            _.setFade();
        }

        _.$slider.trigger('setPosition', [_]);

    };

    Slick.prototype.setProps = function() {

        var _ = this,
            bodyStyle = document.body.style;

        _.positionProp = _.options.vertical === true ? 'top' : 'left';

        if (_.positionProp === 'top') {
            _.$slider.addClass('slick-vertical');
        } else {
            _.$slider.removeClass('slick-vertical');
        }

        if (bodyStyle.WebkitTransition !== undefined ||
            bodyStyle.MozTransition !== undefined ||
            bodyStyle.msTransition !== undefined) {
            if (_.options.useCSS === true) {
                _.cssTransitions = true;
            }
        }

        if ( _.options.fade ) {
            if ( typeof _.options.zIndex === 'number' ) {
                if( _.options.zIndex < 3 ) {
                    _.options.zIndex = 3;
                }
            } else {
                _.options.zIndex = _.defaults.zIndex;
            }
        }

        if (bodyStyle.OTransform !== undefined) {
            _.animType = 'OTransform';
            _.transformType = '-o-transform';
            _.transitionType = 'OTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.MozTransform !== undefined) {
            _.animType = 'MozTransform';
            _.transformType = '-moz-transform';
            _.transitionType = 'MozTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.webkitTransform !== undefined) {
            _.animType = 'webkitTransform';
            _.transformType = '-webkit-transform';
            _.transitionType = 'webkitTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.msTransform !== undefined) {
            _.animType = 'msTransform';
            _.transformType = '-ms-transform';
            _.transitionType = 'msTransition';
            if (bodyStyle.msTransform === undefined) _.animType = false;
        }
        if (bodyStyle.transform !== undefined && _.animType !== false) {
            _.animType = 'transform';
            _.transformType = 'transform';
            _.transitionType = 'transition';
        }
        _.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false);
    };


    Slick.prototype.setSlideClasses = function(index) {

        var _ = this,
            centerOffset, allSlides, indexOffset, remainder;

        allSlides = _.$slider
            .find('.slick-slide')
            .removeClass('slick-active slick-center slick-current')
            .attr('aria-hidden', 'true');

        _.$slides
            .eq(index)
            .addClass('slick-current');

        if (_.options.centerMode === true) {

            var evenCoef = _.options.slidesToShow % 2 === 0 ? 1 : 0;

            centerOffset = Math.floor(_.options.slidesToShow / 2);

            if (_.options.infinite === true) {

                if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) {
                    _.$slides
                        .slice(index - centerOffset + evenCoef, index + centerOffset + 1)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    indexOffset = _.options.slidesToShow + index;
                    allSlides
                        .slice(indexOffset - centerOffset + 1 + evenCoef, indexOffset + centerOffset + 2)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

                if (index === 0) {

                    allSlides
                        .eq( _.options.slidesToShow + _.slideCount + 1 )
                        .addClass('slick-center');

                } else if (index === _.slideCount - 1) {

                    allSlides
                        .eq(_.options.slidesToShow)
                        .addClass('slick-center');

                }

            }

            _.$slides
                .eq(index)
                .addClass('slick-center');

        } else {

            if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {

                _.$slides
                    .slice(index, index + _.options.slidesToShow)
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else if (allSlides.length <= _.options.slidesToShow) {

                allSlides
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else {

                remainder = _.slideCount % _.options.slidesToShow;
                indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;

                if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) {

                    allSlides
                        .slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    allSlides
                        .slice(indexOffset, indexOffset + _.options.slidesToShow)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

            }

        }

        if (_.options.lazyLoad === 'ondemand' || _.options.lazyLoad === 'anticipated') {
            _.lazyLoad();
        }
    };

    Slick.prototype.setupInfinite = function() {

        var _ = this,
            i, slideIndex, infiniteCount;

        if (_.options.fade === true) {
            _.options.centerMode = false;
        }

        if (_.options.infinite === true && _.options.fade === false) {

            slideIndex = null;

            if (_.slideCount > _.options.slidesToShow) {

                if (_.options.centerMode === true) {
                    infiniteCount = _.options.slidesToShow + 1;
                } else {
                    infiniteCount = _.options.slidesToShow;
                }

                for (i = _.slideCount; i > (_.slideCount -
                        infiniteCount); i -= 1) {
                    slideIndex = i - 1;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex - _.slideCount)
                        .prependTo(_.$slideTrack).addClass('slick-cloned');
                }
                for (i = 0; i < infiniteCount  + _.slideCount; i += 1) {
                    slideIndex = i;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex + _.slideCount)
                        .appendTo(_.$slideTrack).addClass('slick-cloned');
                }
                _.$slideTrack.find('.slick-cloned').find('[id]').each(function() {
                    $(this).attr('id', '');
                });

            }

        }

    };

    Slick.prototype.interrupt = function( toggle ) {

        var _ = this;

        if( !toggle ) {
            _.autoPlay();
        }
        _.interrupted = toggle;

    };

    Slick.prototype.selectHandler = function(event) {

        var _ = this;

        var targetElement =
            $(event.target).is('.slick-slide') ?
                $(event.target) :
                $(event.target).parents('.slick-slide');

        var index = parseInt(targetElement.attr('data-slick-index'));

        if (!index) index = 0;

        if (_.slideCount <= _.options.slidesToShow) {

            _.slideHandler(index, false, true);
            return;

        }

        _.slideHandler(index);

    };

    Slick.prototype.slideHandler = function(index, sync, dontAnimate) {

        var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null,
            _ = this, navTarget;

        sync = sync || false;

        if (_.animating === true && _.options.waitForAnimate === true) {
            return;
        }

        if (_.options.fade === true && _.currentSlide === index) {
            return;
        }

        if (sync === false) {
            _.asNavFor(index);
        }

        targetSlide = index;
        targetLeft = _.getLeft(targetSlide);
        slideLeft = _.getLeft(_.currentSlide);

        _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;

        if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        }

        if ( _.options.autoplay ) {
            clearInterval(_.autoPlayTimer);
        }

        if (targetSlide < 0) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll);
            } else {
                animSlide = _.slideCount + targetSlide;
            }
        } else if (targetSlide >= _.slideCount) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = 0;
            } else {
                animSlide = targetSlide - _.slideCount;
            }
        } else {
            animSlide = targetSlide;
        }

        _.animating = true;

        _.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);

        oldSlide = _.currentSlide;
        _.currentSlide = animSlide;

        _.setSlideClasses(_.currentSlide);

        if ( _.options.asNavFor ) {

            navTarget = _.getNavTarget();
            navTarget = navTarget.slick('getSlick');

            if ( navTarget.slideCount <= navTarget.options.slidesToShow ) {
                navTarget.setSlideClasses(_.currentSlide);
            }

        }

        _.updateDots();
        _.updateArrows();

        if (_.options.fade === true) {
            if (dontAnimate !== true) {

                _.fadeSlideOut(oldSlide);

                _.fadeSlide(animSlide, function() {
                    _.postSlide(animSlide);
                });

            } else {
                _.postSlide(animSlide);
            }
            _.animateHeight();
            return;
        }

        if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
            _.animateSlide(targetLeft, function() {
                _.postSlide(animSlide);
            });
        } else {
            _.postSlide(animSlide);
        }

    };

    Slick.prototype.startLoad = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.hide();
            _.$nextArrow.hide();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.hide();

        }

        _.$slider.addClass('slick-loading');

    };

    Slick.prototype.swipeDirection = function() {

        var xDist, yDist, r, swipeAngle, _ = this;

        xDist = _.touchObject.startX - _.touchObject.curX;
        yDist = _.touchObject.startY - _.touchObject.curY;
        r = Math.atan2(yDist, xDist);

        swipeAngle = Math.round(r * 180 / Math.PI);
        if (swipeAngle < 0) {
            swipeAngle = 360 - Math.abs(swipeAngle);
        }

        if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
            return (_.options.rtl === false ? 'right' : 'left');
        }
        if (_.options.verticalSwiping === true) {
            if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
                return 'down';
            } else {
                return 'up';
            }
        }

        return 'vertical';

    };

    Slick.prototype.swipeEnd = function(event) {

        var _ = this,
            slideCount,
            direction;

        _.dragging = false;
        _.swiping = false;

        if (_.scrolling) {
            _.scrolling = false;
            return false;
        }

        _.interrupted = false;
        _.shouldClick = ( _.touchObject.swipeLength > 10 ) ? false : true;

        if ( _.touchObject.curX === undefined ) {
            return false;
        }

        if ( _.touchObject.edgeHit === true ) {
            _.$slider.trigger('edge', [_, _.swipeDirection() ]);
        }

        if ( _.touchObject.swipeLength >= _.touchObject.minSwipe ) {

            direction = _.swipeDirection();

            switch ( direction ) {

                case 'left':
                case 'down':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide + _.getSlideCount() ) :
                            _.currentSlide + _.getSlideCount();

                    _.currentDirection = 0;

                    break;

                case 'right':
                case 'up':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide - _.getSlideCount() ) :
                            _.currentSlide - _.getSlideCount();

                    _.currentDirection = 1;

                    break;

                default:


            }

            if( direction != 'vertical' ) {

                _.slideHandler( slideCount );
                _.touchObject = {};
                _.$slider.trigger('swipe', [_, direction ]);

            }

        } else {

            if ( _.touchObject.startX !== _.touchObject.curX ) {

                _.slideHandler( _.currentSlide );
                _.touchObject = {};

            }

        }

    };

    Slick.prototype.swipeHandler = function(event) {

        var _ = this;

        if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) {
            return;
        } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
            return;
        }

        _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
            event.originalEvent.touches.length : 1;

        _.touchObject.minSwipe = _.listWidth / _.options
            .touchThreshold;

        if (_.options.verticalSwiping === true) {
            _.touchObject.minSwipe = _.listHeight / _.options
                .touchThreshold;
        }

        switch (event.data.action) {

            case 'start':
                _.swipeStart(event);
                break;

            case 'move':
                _.swipeMove(event);
                break;

            case 'end':
                _.swipeEnd(event);
                break;

        }

    };

    Slick.prototype.swipeMove = function(event) {

        var _ = this,
            edgeWasHit = false,
            curLeft, swipeDirection, swipeLength, positionOffset, touches, verticalSwipeLength;

        touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;

        if (!_.dragging || _.scrolling || touches && touches.length !== 1) {
            return false;
        }

        curLeft = _.getLeft(_.currentSlide);

        _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
        _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;

        _.touchObject.swipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));

        verticalSwipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));

        if (!_.options.verticalSwiping && !_.swiping && verticalSwipeLength > 4) {
            _.scrolling = true;
            return false;
        }

        if (_.options.verticalSwiping === true) {
            _.touchObject.swipeLength = verticalSwipeLength;
        }

        swipeDirection = _.swipeDirection();

        if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
            _.swiping = true;
            event.preventDefault();
        }

        positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
        if (_.options.verticalSwiping === true) {
            positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
        }


        swipeLength = _.touchObject.swipeLength;

        _.touchObject.edgeHit = false;

        if (_.options.infinite === false) {
            if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) {
                swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
                _.touchObject.edgeHit = true;
            }
        }

        if (_.options.vertical === false) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        } else {
            _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset;
        }
        if (_.options.verticalSwiping === true) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        }

        if (_.options.fade === true || _.options.touchMove === false) {
            return false;
        }

        if (_.animating === true) {
            _.swipeLeft = null;
            return false;
        }

        _.setCSS(_.swipeLeft);

    };

    Slick.prototype.swipeStart = function(event) {

        var _ = this,
            touches;

        _.interrupted = true;

        if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
            _.touchObject = {};
            return false;
        }

        if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
            touches = event.originalEvent.touches[0];
        }

        _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
        _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;

        _.dragging = true;

    };

    Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() {

        var _ = this;

        if (_.$slidesCache !== null) {

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.unload = function() {

        var _ = this;

        $('.slick-cloned', _.$slider).remove();

        if (_.$dots) {
            _.$dots.remove();
        }

        if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
            _.$prevArrow.remove();
        }

        if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
            _.$nextArrow.remove();
        }

        _.$slides
            .removeClass('slick-slide slick-active slick-visible slick-current')
            .attr('aria-hidden', 'true')
            .css('width', '');

    };

    Slick.prototype.unslick = function(fromBreakpoint) {

        var _ = this;
        _.$slider.trigger('unslick', [_, fromBreakpoint]);
        _.destroy();

    };

    Slick.prototype.updateArrows = function() {

        var _ = this,
            centerOffset;

        centerOffset = Math.floor(_.options.slidesToShow / 2);

        if ( _.options.arrows === true &&
            _.slideCount > _.options.slidesToShow &&
            !_.options.infinite ) {

            _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
            _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            if (_.currentSlide === 0) {

                _.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            }

        }

    };

    Slick.prototype.updateDots = function() {

        var _ = this;

        if (_.$dots !== null) {

            _.$dots
                .find('li')
                    .removeClass('slick-active')
                    .end();

            _.$dots
                .find('li')
                .eq(Math.floor(_.currentSlide / _.options.slidesToScroll))
                .addClass('slick-active');

        }

    };

    Slick.prototype.visibility = function() {

        var _ = this;

        if ( _.options.autoplay ) {

            if ( document[_.hidden] ) {

                _.interrupted = true;

            } else {

                _.interrupted = false;

            }

        }

    };

    $.fn.slick = function() {
        var _ = this,
            opt = arguments[0],
            args = Array.prototype.slice.call(arguments, 1),
            l = _.length,
            i,
            ret;
        for (i = 0; i < l; i++) {
            if (typeof opt == 'object' || typeof opt == 'undefined')
                _[i].slick = new Slick(_[i], opt);
            else
                ret = _[i].slick[opt].apply(_[i].slick, args);
            if (typeof ret != 'undefined') return ret;
        }
        return _;
    };

}));
;
/*
* 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;
var urlp = "";
var originalFontSize = jQuery(".MsoNormal").css("font-size");
var max = 4;
var min = -3;
var fixMegadropdowMenu = false;
var HASPageOffset = 50;
var GoogleApiKey = "xxx";
var GTag = 'G-6BYPT8DSKX';
var SITENAME = 'MINAE';
var idAddThis = 'ra-636e6779fe620564'
var CollapseDataTablesGroupsByDefault = true;

var MoverSliderHome = function () {
    var $firstSlider = jQuery("img[alt*='?ext=slider']:first");
    var $sliderParent = $firstSlider.parents("p:first");
    if (jQuery("#ctl00_SliderHome").length > 0) {
        jQuery("#ctl00_SliderHome").append($firstSlider);
        $sliderParent.remove();
    }
};

var SetupContextImage = function () {
    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>"
            );
    }
};




RevisarDependencias();
function llamadosHermes(sitio) {
    //TODO: ver que intencion tiene esto...
    if (urlp != "") urlp = "/redirect.php?URL=http://" + urlp;

    //Cambio de color basico
    //window.SetuColorChangeSetuppFontResize !== undefined && ColorChangeSetup();

    // Ya en Sufef no se utiliza esta funcionalidad de pasar el primer slider
    //MoverSliderHome();


    $('tr[style*="height"], td[style*="height"]')
        .css({ height: '' });

    ReplaceLinksWithContent(function () {
        convertHermesContainer();

        jQuery("div[id*='_MenuPiePagina_'] a, div[id*='_MenuContextual_'] a")
            .attr("tabindex", "0")
            .attr("aria-expanded", "true");

        SetupContextImage();
        fixFooterMenu();
        fixLeftSideBarMenu();

        window.fixImagesForResponsive !== undefined && fixImagesForResponsive();
        window.fixLayout !== undefined && fixLayout();
        window.fixForms !== undefined && fixForms();
        //TODO: Duplicado en Utils.js
        //window.InitDatepicker !== undefined && InitDatepicker();
        window.TabsHistory !== undefined && TabsHistory();
        window.SetupFontResize !== undefined && SetupFontResize();
        window.SetupMegadropdowMenu !== undefined && SetupMegadropdowMenu();
        window.SetupPaginaIntermedia !== undefined && SetupPaginaIntermedia();

        //CalculateMenuWidth();

        setTimeout(function () {
            if (typeof AfterConvertHermesContainerCallbacks != "undefined") {
                for (i = 0; i < AfterConvertHermesContainerCallbacks.length; i++) {
                    AfterConvertHermesContainerCallbacks[i]();
                }
                jQuery("#ctl00_SliderHome img").on("load", function () {
                    jQuery(window).scroll();
                });
            }
            window.SetupRSSWidget !== undefined && SetupRSSWidget();			
        }, 500);
    });

    //SetupUserControls
    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);
    });

    /////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();
        });
    });
}

//////////////
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 CalculateMenuWidth() {
//    var lis = $(".MenuTop .nav.navbar-nav > li");
//    var newWidth = 100 / lis.length;
//    lis.css({ 'width': newWidth + '%' });
//}
//Funcion para cuando el contenido de un modal es muy largo

jQuery(document).ready(function () {
    var maxHeight = $(window).height() - 160;
    jQuery(".modal-body").css("max-height", maxHeight);

    var menuIdx = 0;
    $("nav.navbar").each(function () {
        var menuId = "HNavBar" + menuIdx++;
        var $thisNavBar = $(this);
        $thisNavBar
            .find("button.navbar-toggler")
            .attr("data-bs-target", "#" + menuId);
        $thisNavBar.find("div.navbar-collapse").attr("id", menuId);
        $thisNavBar.find(".menuImage").each(function () {
            var $currentImageMenuItem = $(this);
            var $newImageItem = $("<img >", {
                class: "menuImage",
                onmouseout: "AlternarImagen(this)",
                onmouseover: "AlternarImagen(this)",
                src: $currentImageMenuItem.data("src"),
                alt: $currentImageMenuItem.data("alt"),
            });
            $currentImageMenuItem.before($newImageItem);
            $currentImageMenuItem.remove();
        });
    });

    //Funcion para cuando los tabs se exceden el ancho del contenedor
    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" });
            }
        });
    }
});

window.SetupBuscador !== undefined && SetupBuscador();
//OnScroll
window.SetupOnScroll !== undefined && SetupOnScroll();

//MultiLevelMenus
window.SetupMultiLevelMenus !== undefined && SetupMultiLevelMenus();

//window.SetupAsistenteVirtual !== undefined && SetupAsistenteVirtual();

//GoogleAnalytics
window.SetupGoogleAnalytics !== undefined && SetupGoogleAnalytics(GTag);

try {
    jQuery(document).ready(function () {
        llamadosHermes(SITENAME);
        jQuery.slidebars();
    });

    jQuery(window).resize(function () {
        //jQuery.slidebars.close()
    });
}
catch (e) {
    console.log(e.message);
};
