// *** 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;
}

function omitirAcentos(text) {
    var acentos = "ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç";
    var original = "AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc";
    for (var i = 0; i < acentos.length; i++) {
        text = text.replace(acentos.charAt(i), original.charAt(i));
    }
    return text;
}
;
/* 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;
}



/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {
    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    // public method for encoding
    encode: function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = Base64._utf8_encode(input);
        while (i < input.length) {
            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 +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },
    // public method for decoding
    decode: function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._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);
            }
        }
        output = Base64._utf8_decode(output);
        return output;
    },
    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

//http://techslides.com/how-to-parse-and-search-json-in-javascript
//return an array of objects according to key, value, or key and value matching
function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            if (getObjects(obj[i], key, val).length > 0) {
                objects.push(obj[i]);
            }
//            objects = objects.concat(getObjects(obj[i], key, val));
        } else
            //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
            if (i == key && obj[i] == val || i == key && val == '') { //
                objects.push(obj);
            } else if (obj[i] == val && key == '') {
                //only add if the object is not already in the array
                if (objects.lastIndexOf(obj) == -1) {
                    objects.push(obj);
                }
            }
    }
    return objects;
}

//return an array of values that match on a certain key
function getValues(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getValues(obj[i], key));
        } else if (i == key) {
            objects.push(obj[i]);
        }
    }
    return objects;
}

//return an array of keys that match on a certain value
function getKeys(obj, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getKeys(obj[i], val));
        } else if (obj[i] == val) {
            objects.push(i);
        }
    }
    return objects;
}



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", "/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").remove();
    jQuery(":submit").not(".BotonVisible").remove();

    // elimina todos los contenedores de botones de DataTableTools (crear, eliminar, editar)
    //jQuery(".DTTT_container").remove();
    RedefinirDTTT_container();

    // deshabilita controles de captura
    jQuery(":checkbox").attr("disabled", "disabled");
    jQuery(":checkbox").addClass("readOnlyMode");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv :checkbox", "input");

    jQuery(":radio").attr("disabled", "disabled");
    jQuery(":radio").addClass("readOnlyMode");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv :radio", "radio");

    jQuery("select").attr("disabled", "disabled");
    jQuery("select").addClass("readOnlyMode");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv select", "select");

    jQuery("textarea").attr("disabled", "disabled");
    jQuery("textarea").addClass("readOnlyMode");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv :text", "input");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv textarea", "input");
    ReemplazarControlesPorLabel(".MainContentPlaceDiv input[type='number']", "input");

    jQuery(":text").attr("disabled", "disabled");
    jQuery(":text").addClass("readOnlyMode");
    jQuery(":text").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 DetachValidationEngine() {
    jQuery('.MainForm').validationEngine('detach');
}

function ActivateInPlaceEditing() {
    var oldValue;
    var newValue;

    jQuery('.editArea').editable('/App_HttpHandlers/InPlaceEditing/UpdateField.ashx', {
        type: 'textarea',
        cancel: 'Cancelar',
        submit: 'Guardar',
        indicator: '<img src="/images/loadingIcon-inline.gif">',
        tooltip: 'Clic para editar ...',
        onsubmit: function (settings, original) {
            //
        },
        data: function (value, settings) {
            /* convert <br> to newline */
            var retval = value.replace(/<br[\s\/]?>/gi, '\n');
            return retval;
        },
        submitdata: function (value, settings) {
            /* HTML5 Custom Data Attributes (data-*) http://html5doctor.com/html5-custom-data-attributes/ */
            var itemid = jQuery(this).attr('data-idp-itemid');
            var code = jQuery(this).attr('data-idp-code');

            oldValue = this.revert;

            return {
                itemid: itemid,
                code: code
            };
        },
        callback: function (value, settings) {
            var object = jQuery(this);
            var data = jQuery.parseJSON(value);

            if (data.result == "1") {
                newValue = data.value;
                // set new value
                object.html(newValue);
                // user message
                var controlId = '#' + object.attr('id');
                ShowSuccessMessageLabel("Listo!", controlId);

                SuccessMessage(data.errormessage);
            } else {
                // restore old value
                object.html(oldValue);

                // error message
                ErrorMessage(data.errormessage);
            }

            // reset vars
            oldValue = "";
            newValue = "";
        }
    });
}

function IsEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

jQuery.fn.hasAttr = function (name) {
    return this.attr(name) !== undefined;
};
// bitacora
function MostrarBitacora(key1, key2, objeto) {
    //objeto debe venir schema.[tabla], o bien [tabla] cuando se usa dbo

    var initBitacoraModal = function (key1, key2, objeto) {
        var key2Filtro = 1;
        var key2Value = 1;
        if (key2 != null) {
            key2Filtro = 'key2';
            key2Value = key2;
        }
        $('#ViewAuditoriaTable').customeditor({
            dataTablesKey: "MantenimientoViewAuditoria",
            readOnly: true,
            dataTablesColumns:
            [
                { data: 'id' },
                { data: 'fechahora' },
                {
                    data: 'evento',
                    "render":
                        function (val, type, row) {
                            if (val == 3)
                                return "Editar";
                            else if (val == 1)
                                return "Insertar";
                            else if (val == 2)
                                return "Eliminar";
                            else
                                return val + "Consultar";
                        }
                },
                { data: 'idUser' },
                { data: 'ip' },
                {
                    data: 'campos',
                    "render":
                        function (val, type, row) {
                            //faster than the Regexp version http://jsperf.com/replace-all-vs-split-join
                            return val.split('|').join(' | '); //reemplazar todos para favorecer wrap text                            
                        }
                }
            ],
            filters: [
                { key: 'key1', value: key1, operator: '=' },
                { key: key2Filtro, value: key2Value, operator: '=' },
                { key: 'objeto', value: objeto, operator: '=' }
            ]
        });

        // get plugin data
        var viewAuditoriaPluginData = $('#ViewAuditoriaTable').customeditor('getData');

        // update filters
        viewAuditoriaPluginData.filters = [
            { key: 'key1', value: key1, operator: '=' },
            { key: key2Filtro, value: key2Value, operator: '=' },
            { key: 'objeto', value: objeto, operator: '=' }
        ]

        if (viewAuditoriaPluginData.isReady) {
            // reload data
            var table = $('#ViewAuditoriaTable').DataTable();
            table.ajax.reload();
            // sort by columns 1, and redraw
            table
                .order([1, 'desc'])
                .draw();
        }
        else {
            // init plugin
            $('#ViewAuditoriaTable').customeditor('initEditor');
        }

        // show modal
        $('#bitacoraModal').modal('show');
    };

    if ($('#bitacoraModal').length === 0) {
        // cargar Html del modal
        jQuery.ajax({
            url: "/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 "";
}

// Helper function to get 'now' as an ISO date string
function IsoDateString() {
    var d = new Date();
    var pad = function (n) {
        return n < 10 ? '0' + n : n
    }

    return pad(d.getUTCDate()) + '/'
        + pad(d.getUTCMonth() + 1) + '/'
        + pad(d.getUTCFullYear())
};

function IsoDateTimeString() {
    var d = new Date();

    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 + ":" + s + ampm;
};

function InitDatepicker() {
    jQuery("input[data-datepicker] , .FechaJQuery").datepicker({
        format: "dd/mm/yyyy",
        todayBtn: true,
        language: "es",
        autoclose: true,
        todayHighlight: true
    });
}

function InitDateTimePicker() {
    var initDate = new Date();
    initDate.setSeconds(0);

    jQuery("input[data-datetimepicker] , .FechaHoraJQuery").datetimepicker({
        format: "dd/mm/yyyy HH:ii:ss P",
        language: "es",
        autoclose: true,
        showMeridian: true,
        initialDate: initDate
    });
}

function InitializePopover() {
    $('[data-toggle="popover"]').popover({ trigger: 'focus' });
}

var GetIndexIfObjWithAttr = function (array, attr, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][attr] == value) {
            return i;
        }
    }
    return -1;
}


$(document).ready(function () {
    if (typeof $.fn.datepicker != "undefined") {
        InitDatepicker();
    }
    if (typeof $.fn.datetimepicker != "undefined") {
        InitDateTimePicker();
    }

    if (typeof pageMode != 'undefined') {
        if (pageMode === PAGEMODE_READONLY) {
            ActivarReadOnlyMode();
        } else {
            SetControlToReadOnly();//si la página no es readonly, pueden haber controles que si lo sean
        }
    }
});

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 CreateModal($parent, title, content, buttons, shownCallback, closeCallback, destroyOnClose, beforeCloseCallback) {
    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('hide.bs.modal', function (e) {
        var closeResult = true;
        if (beforeCloseCallback !== undefined && beforeCloseCallback != null) {
            closeResult = beforeCloseCallback($modal);
        }
        if (!closeResult) {
            e.preventDefault();
            e.stopImmediatePropagation();
        }
        return closeResult;
    });
    $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;
}
;
// prevent a Form submir with ENTER
document.onkeypress = function (objEvent) {
    if (!objEvent)
        var objEvent = window.event; // IE
    if (objEvent === undefined)
        objEvent = window.event; // fix IE

    // check if the target is a textarea element
    var elem = (objEvent.target) ? objEvent.target : objEvent.srcElement;
    if (elem.type == "textarea") {
        // a textarea has the focus, allow Enter
        return true;
    }

    if (elem.tagName == "A") {
        // a textarea has the focus, allow Enter
        return true;
    }

    if (objEvent.keyCode == 13) // enter key
    {
        var target = objEvent.target;
        if (!target)
            target = objEvent.srcElement; // fix IE
        if (objEvent === undefined)
            target = objEvent.srcElement; // fix IE

        var control = jQuery("#" + target.id);
        var controlType = control.attr("type");
        if (controlType == "password") {
            jQuery(".LoginSubmitButton").click();
        }


        return false; // this will prevent bubbling ( sending it to children ) the event!
    }
}

function FixRadioStyle() {
    jQuery(":radio").css("border", "none");
    jQuery(":radio").each(function () {
        $(this).after("&nbsp;");
    });

    jQuery(":checkbox").css("border", "none");
    jQuery(":checkbox").each(function () {
        $(this).after("&nbsp;");
    });
}
;
var urlp = "";
var originalFontSize = jQuery('.MsoNormal').css('font-size');
var max = 4;
var min = -3;
var provinciasArray = ['San José', 'Alajuela', 'Cartago', 'Heredia', 'Guanacaste', 'Puntarenas', 'Limón'];
var temasArray = ['Administración', 'Arquitectura', 'Artes plásticas', 'Bibliotecología',
    'Ciencias exactas', 'Ciencias naturales', 'Comercio', 'Comunicación y transporte',
    'Deportes', 'Economía', 'Educación', 'Estadísticas', 'Farmacia',
    'Filosofía', 'Geografía', 'Historia', 'Humor gráfico', 'Idiomas y lenguas',
    'Ingeniería', 'Legislación', 'Lingüística', 'Literatura', 'Masonería', 'Medicina', 'Música',
    'Periodismo', 'Personajes ilustres', 'Política', 'Religión', 'Sociedad y aspectos sociales',
    'Sociología', 'Tecnología', 'Tradiciones y costumbres'];
var mesesArray = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "setiembre", "octubre", "noviembre", "diciembre"];
var esPeriodico = false;
var esRevista = false;
var idpagina = null;
var GoogleApiKey = 'AIzaSyB5qXI0IR4pG4614dFdGzKywaAxfBEZWDk';
var GTag = 'G-0PSBBE442D';

RevisarDependencias();


if (jQuery("img[alt *= 'playlist']").length > 0 ) {
    include("/js/buscadorplaylist.js",{dom:true});
}


function llamadosHermes(sitio) {
    if (urlp != "")
        urlp = "/redirect.php?URL=http://" + urlp;

    //Cambio de color basico
    //ColorChangeSetup();
    jQuery(".WordSection1 img,.nav img, #PageContent img").addClass("img-responsive");

    ReplaceLinksWithContent(function () {
        //Reemplazar los links de pdfs de biblioteca digital
        jQuery("a[href*='/biblioteca%20digital/'],a[href*='/biblioteca digital/'],a[href*='/Biblioteca Digital/'],a[href*='/Biblioteca%20Digital/']")
            .not("a.playVideo,a.VerArchivo,a[href^='http'],a[href^='/ver/'],a[href$='/'], a[href*='.aspx'],a[href*='.html'],.free-wall a, a[rel^='lightbox'],.HASBreadCrumbs a").each(function () {
                var $this = jQuery(this);
                $this.attr('href', '/ver' + $this.attr('href'));
            });
        if (jQuery("#ficha, .FichaArchivoContainer").length == 0) {
            jQuery(".addOns").after("<div class='clear'></div>");
        }


        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);
                    }

                    esPeriodico = jQuery(".CategoriasDiv a[href$='CATEGORIAS=12']").length > 0;
                    esRevista = jQuery(".CategoriasDiv a[href$='CATEGORIAS=13']").length > 0;

                    jQuery(".CategoriasDiv ul").each(function () {
                        var $thisUL = jQuery(this);
                        if ($thisUL.text() == "") {
                            $thisUL.hide();
                        }
                    });

                    if (typeof ($CategoriasPaginaDiv) != 'undefined') {
                        $CategoriasPaginaDiv.show();
                    }

                    if (typeof (RenderEdicionesSiguienteAnterior) != 'undefined') {
                        RenderEdicionesSiguienteAnterior();
                    }
                }
            });
        }


        convertHermesContainer();

        jQuery(".panel-group").each(function () {
            var $this = jQuery(this);
            $this.find("a[data-toggle='collapse']:first").click();
        });

        if (typeof AfterConvertHermesContainerCallbacks != 'undefined') {
            for (i = 0; i < AfterConvertHermesContainerCallbacks.length; i++) {
                AfterConvertHermesContainerCallbacks[i]();
            }
        }


        jQuery("div[id*='_MenuPiePagina_'] a, div[id*='_MenuContextual_'] a").attr("tabindex", "0").attr("aria-expanded", "true");

        fixFooterMenu();
        fixLeftSideBarMenu();
        fixLayout();
        fixForms();
        InitDatepicker();
        TabsHistory();
        SetupFontResize();


        jQuery("#expresion").keypress(function (e) {
            if (e.which == 13) {
                jQuery("#BuscarButtonHeader").click();
            }
        });


        try {
            include("/js/contextMenuON.js", { dom: true });
        }
        catch (ex) {

        }

        //////FIXES megadropdown-menu ///////////////////////
        if ((typeof (fixMegadropdowMenu) != "undefined") && fixMegadropdowMenu) {
            var navbarWidth = jQuery(".navbar").get(0).clientWidth;
            var navbarCenter = navbarWidth / 2;
            var colsize = navbarWidth / 6;
            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" });
                }
            });
        }

        var $rssWidget = jQuery("#rssWidget");
        if ($rssWidget.length > 0) {
            jQuery.ajax({
                url: "/App_HttpHandlers/getExterno.ashx?key=widget",
                async: true,
                dataType: 'json',
                success: function (data) {
                    $rssWidget.html("<ul id='fade' class='noticiasticker'>");
                    var $ul = jQuery(".noticiasticker");
                    var $currentLi;
                    var $currentRow;
                    var itemDate;
                    var pubDate;
                    jQuery(data).each(function () {
                        $currentRow = this;
                        $currentLi = jQuery("<li><span class='RSSItem'></span></li>");

                        itemDate = Date.parse($currentRow.props[0]["prop6"]);
                        $currentLi.append("<span class='TipoPub'>" + $currentRow.cats[0]["cat11"] + "</span>");

                        if (itemDate) {
                            $currentLi.append("<span class='RSSDate'>" + itemDate.toString("dd-MM-yyyy") + "</span>");
                        }

                        $currentLi.append("<span class='clear'></span>");

                        pubDate = "";
                        if (typeof $currentRow.atribs[0] != 'undefined') {

                            if ($currentRow.atribs[0]["atrib3"]) {
                                if ($currentRow.atribs[0]["atrib14"]) {
                                    pubDate += "&nbsp;" + $currentRow.atribs[0]["atrib14"];
                                }
                                if ($currentRow.atribs[0]["atrib4"]) {
                                    pubDate += "&nbsp;" + $currentRow.atribs[0]["atrib4"];
                                }
                                pubDate += "&nbsp;" + $currentRow.atribs[0]["atrib3"];
                                $currentLi.append("<span class='PubDate'>Publicado:&nbsp;" + pubDate + "</span>");
                            }

                            if ($currentRow.atribs[0]["atrib5"]) {
                                $currentLi.append("<span class='PubVol'> Vol.:&nbsp;" + $currentRow.atribs[0]["atrib5"] + "</span>");
                            }
                            if ($currentRow.atribs[0]["atrib6"]) {
                                $currentLi.append("<span class='PubNo'> No.:&nbsp;" + $currentRow.atribs[0]["atrib6"] + "</span>");
                            }

                            if ($currentRow.atribs[0]["atrib1"]) {
                                $currentLi.append("<span class='AutorPub'>Autor:&nbsp;" + $currentRow.atribs[0]["atrib1"] + "</span>");
                            }
                            if ($currentRow.atribs[0]["atrib8"]) {
                                $currentLi.append("<span class='CompositorPub'>Compositor:&nbsp;" + $currentRow.atribs[0]["atrib8"] + "</span>");
                            }
                            if ($currentRow.atribs[0]["atrib7"]) {
                                $currentLi.append("<span class='InterpretePub'>Interprete:&nbsp;" + $currentRow.atribs[0]["atrib7"] + "</span>");
                            }
                            if ($currentRow.atribs[0]["atrib11"]) {
                                $currentLi.append("<span class='FotografoPub'>Fot&oacute;grafo;:&nbsp;" + $currentRow.atribs[0]["atrib11"] + "</span>");
                            }
                        }

                        $currentLi.append("<span class='HomeRSSTitulo'><a href='" + $currentRow.link + "'>" + $currentRow.props[0]["prop1"] + "</a>");
                        $currentLi.append("<span class='clear'></span>");

                        $ul.append($currentLi);
                    });
                    LoadHomeNewsWidget();
                }
            });

        }


    });


    jQuery(".Section1 img[alt^='UserControl:'], .WordSection1 img[alt^='UserControl:']").each(function () {
        var $this = jQuery(this);
        var userControlName = this.alt.replace("UserControl:", "");
        var $userControl = jQuery("#" + userControlName);
        $this.replaceWith($userControl);
    });


    $(".addOns:first").append("<div><span class='pull-right'>compartir contenido</span><div class='addthis_inline_share_toolbox'></div>");

    /////esto no se debe borrar, sirve para abrir los acordeones desde el mapa
    jQuery(document).ready(function () {
        $(window).on('hashchange', function (e) {
            var selecctedHash = window.location.hash;
            var currentHref = window.location.pathname;
            var url = currentHref + selecctedHash;
            jQuery("a[href^='" + selecctedHash + "']").click();
        });
    });
}


/*****07-Sep-2017 J.Cedeno cambia color de campos requeridos y al placeholder le agrega el texto*****/
if (typeof __HermesRequeridos !== 'undefined') {
    for (i = 0; i <= __HermesRequeridos.length - 1; i++) {
        jQuery("#" + __HermesRequeridos[i]).css("background-color", "#ffe8e8");
        aPlaceholder = jQuery("#" + __HermesRequeridos[i]).attr("placeholder");
        if (aPlaceholder !== null || aPlaceholder !== '') {
            jQuery("#" + __HermesRequeridos[i]).attr("placeholder", aPlaceholder + " - Requerido");
        }
        else
            jQuery("#" + __HermesRequeridos[i]).attr("placeholder", "Valor Requerido");
    }
}



if (jQuery("img[alt$='PeriodicosDelDia.htm']").length > 0) {
    //    include("/js_srv/dataTables/jquery.dataTables.js", { dom: true });
    include("/js_srv/incluir_dataTablesCustomList.js", { dom: true });

}

//////////////
function fixForms() {
    jQuery(".WordSection1 input:not([type=radio],[type=checkbox]),.WordSection1 select,.WordSection1 textarea").each(function () {
        var $this = jQuery(this);
        var $newFormGroup = jQuery("<div class='form-group'>");
        var $pContainer = $this.parents("p").eq(0);
        var controlClass = "";
        switch ($this.attr("type")) {
            case "button":
            case "submit": controlClass = "btn"; break;
            default: controlClass = "form-control";
        }

        $this.addClass(controlClass);
        if (typeof ($pContainer) != 'undefined') {
            $pContainer.before($newFormGroup);
            $newFormGroup.append($pContainer.contents());
            $pContainer.remove();
        }
    });
}

function fixLayout() {
    var exceptions = ".TableNoConvertToDiv,table[id^='HASCustomList_'] ,.indice_contenido,.dataTable ,.SimpleDataTable,.HERMESCUSTOMLIST,.HERMESIGNORETABLETOGRID,.HERMESACCORDION,.HERMESTABS,.HERMESVTABS,.HERMESFORMS,.ui-jqgrid-btable,.ui-jqgrid-htable,.ui-pg-table,.ui-pg-table,.datetimepicker,.customeditor";
    jQuery("table").not(exceptions).each(function () {
        var $currentTable = jQuery(this);
        var $newConvertedTable = jQuery("<div class='TableConverted'>");

        var SpanColsByRowSpanArray = new Array;
        if ($currentTable.parents(exceptions).length == 0) {
            $currentTable.find(" > tbody > tr").each(function () {
                var $currentRow = jQuery(this);
                var $rowCols = $currentRow.find(">td");
                var cols = $rowCols.length;
                var $newRow = jQuery("<div class='row'>");
                var colClass = "";

                var colSpan = 0;
                $currentRow.find(">td[colspan]").each(function () {
                    colSpan += (jQuery(this).attr("colspan") * 1) - 1;
                });
                cols += colSpan;

                switch (cols) {
                    case 1: colClass = "col-xs-12 overflowHidden"; break;
                    case 2: colClass = "col-sm-6 text-left-sm text-left-xs overflowHidden"; break;
                    case 3: colClass = "col-sm-4 text-left-sm text-left-xs overflowHidden"; break;
                    case 4: colClass = "col-sm-3 text-left-xs overflowHidden"; break;
                    case 6: colClass = "col-sm-2 text-left-xs overflowHidden"; break;
                    case 12: colClass = "col-sm-1 text-left-xs overflowHidden"; break;
                }

                $rowCols.each(function () {
                    var $currentCol = jQuery(this);
                    var thisColClass = colClass;

                    colSpan = $currentCol.attr('colspan');
                    if (colSpan) {
                        var x = Math.round(colSpan / cols * 12);
                        //alert(x);
                        thisColClass = "col-sm-" + x + " text-left-sm text-left-xs overflowHidden";
                    }



                    var thisRowSpan = $currentCol.attr("rowspan") * 1;
                    var $newCol = jQuery("<div>");
                    $newCol.addClass(thisColClass);

                    $newCol.append($currentCol.contents());
                    $newRow.append($newCol);
                    if (thisRowSpan) {
                        $newCol.attr("data-rowspan", thisRowSpan);
                        SpanColsByRowSpanArray.push(thisRowSpan);
                    }

                });
                //Ignorar celdas vacios
                if (jQuery.trim($newRow.text()) != "" ||
                    ($newRow.find("video,audio,iframe,img,input,textarea,button,select").length > 0)) {
                    $newConvertedTable.append($newRow);
                }
            });


            $currentTable.before($newConvertedTable);
            $currentTable.remove();

            jQuery("div[data-rowspan]").each(function () {
                var $this = jQuery(this);
                console.log("data-rowspan" + $this.attr("data-rowspan"));
            });
        }
    });


    jQuery("table.HERMESIGNORETABLETOGRID").each(function () {
        var $thisTable = jQuery(this);
        $thisTable.after($thisTable.find("tr:nth-child(2) > td:first > *"));
        $thisTable.remove();
    });

}



function fixFooterMenu() {
    var $footerMenu = jQuery("footer .nav ");
    $footerMenu.find(".dropdown").removeClass("dropdown mega-dropdown");
    $footerMenu.find(".dropdown-toggle").removeClass("dropdown-toggle");
    $footerMenu.find(".dropdown-menu").removeClass("dropdown-menu mega-dropdown-menu");
    $footerMenu.find(".caret").remove();
}


function fixLeftSideBarMenu() {
    var $LeftSideBarMenu = jQuery(".LeftSideBarContainer .nav ");
    $LeftSideBarMenu.find(".dropdown").removeClass("dropdown mega-dropdown");
    $LeftSideBarMenu.find(".dropdown-toggle").removeClass("dropdown-toggle");
    $LeftSideBarMenu.find(".dropdown-menu").removeClass("dropdown-menu mega-dropdown-menu");
    $LeftSideBarMenu.find(".caret").remove();
}

function CambiarAction(boton) {
    if (boton == document.getElementById("botonBuscarMobile")) {
        $("#expresion").val($("#expresionMobile").val());

    }

    var form = $("#aspnetForm");
    form.prop("action", "/default.aspx");

    var vs = document.getElementById("__VIEWSTATE");
    if (typeof (vs) != "undefined") { vs.value = ""; }
}
function InitDatepicker() {
    if (typeof $.fn.datepicker == "undefined") { return; }

    jQuery("input[data-datepicker] , .FechaJQuery").datepicker({
        format: "dd/mm/yyyy",
        todayBtn: true,
        language: "es",
        autoclose: true,
        todayHighlight: true
    });
}

function TabsHistory() {
    if (location.hash !== '') {
        var targetTab = $('a[href="' + location.hash + '"]');
        targetTab.parents("[role='tabpanel']").each(function () {
            jQuery('a[href="#' + this.id + '"]').tab('show');
        });
        targetTab.tab('show');
    }

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        location.hash = $(e.target).attr('href').substr(1);
    })
}



////////////////////////////////
include("/js/jquery/jquery.transform.js", { dom: true });
function RenderRSSWidget(selector, currentXML, isHome) {
    var currentXSL = isHome ? "/xsl/rssHome.xsl" : "/xsl/noticias.xsl";

    if (jQuery(selector).length == 0)
        return;

    jQuery(selector).transform({
        xml: currentXML, xsl: currentXSL,
        complete: function () {
            LoadHomeNewsWidget();
            var itemDate;
            jQuery(selector + " .RSSDate").each(function () {

                var tmpstr = jQuery(this).text().replace(/gmt|,/g, "");
                //alert(tmpstr);
                itemDate = Date.parse(tmpstr);
                itemDate = new Date(itemDate);
                //alert(itemDate);

                if (itemDate > new Date()) {
                    jQuery(jQuery(this).parent()).hide();
                }
                jQuery(this).text(itemDate.toString("dd-MM-yyyy"));
            });
        }
    });
}


function RenderWidget(selector, currentXML, currentXSL) {
    jQuery(selector).transform({
        xml: currentXML, xsl: currentXSL,
        complete: function () { }
    });
}


function displayInWidget(selector, attr, URL) {
    jQuery(selector).attr(attr, URL);
}



//////////////////////////////////////////////////

function LoadHomeNewsWidget() {
    $RSSWidget = jQuery('#rssWidget');
    $RSSWidget.vTicker({
        speed: 1000,
        pause: 8000,
        showItems: 4,
        animation: 'fade',
        mousePause: true,
        height: 364,
        direction: 'up'
    });


    jQuery(".rssWidgetNext").click(function (event) {
        event.preventDefault();
        $RSSWidget.vTicker('next', { animate: true });
    });
    jQuery(".rssWidgetPrev,.rssWidgetNext").hover(function () {
        $RSSWidget.vTicker('pause', true);
    }, function () {
        $RSSWidget.vTicker('pause', false);
    });
    jQuery(".rssWidgetPrev").click(function (event) {
        event.preventDefault();
        $RSSWidget.vTicker('prev', { animate: true });
    });

}



/////////////////////////////////

function SetupFontResize() {
    jQuery(".resetFont").click(function () {
        ResetFont(originalFontSize);
        return false;
    });
    // Increase Font Size
    jQuery(".increaseFont").click(function () {
        IncreaseFont(max);
        return false;
    });
    // Decrease Font Size
    jQuery(".decreaseFont").click(function () {
        DecreaseFont(min);
        return false;
    });
    ResizeFont();
}



function DecreaseFont(min) {
    var val = GetResizeFontCookie();
    if (val > min) {
        var currentFontSize = jQuery('.PrincipalContentContainer p').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum * 0.85;
        jQuery('.PrincipalContentContainer p').css('font-size', newFontSize);
        SetResizeFontCookie(val - 1);
    }
}

function IncreaseFont(max) {
    var val = GetResizeFontCookie();
    if (val < max) {
        var currentFontSize = jQuery('.PrincipalContentContainer p').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum * 1.15;
        jQuery('.PrincipalContentContainer p').css('font-size', newFontSize);
        SetResizeFontCookie(val + 1);
    }
}

function ResetFont(originalFontSize) {
    SetResizeFontCookie(0);
    jQuery('.PrincipalContentContainer p').css('font-size', originalFontSize);
}

function ResizeFont() {
    var val = GetResizeFontCookie();
    if (val > 0) {
        for (i = 0; i < val; i++) {
            IncreaseFont(100);
        }
    }
    else if (val < 0) {
        for (i = 0; i > val; i--) {
            DecreaseFont(-100);
        }
    }
    SetResizeFontCookie(val);
}

function GetResizeFontCookie() {
    if (jQuery.cookie("fontresize") != null) {
        return parseInt(jQuery.cookie("fontresize"));
    }
    else {
        return 0;
    }
}

function SetResizeFontCookie(val) {
    jQuery.cookie("fontresize", val, { path: '/', expires: 2 })
}


function ColorChangeSetup() {
    var currentColor = GetColorChangeCookie();
    jQuery("head").append("<link rel='stylesheet' id='ColorChange' href='/css/cambio/" + currentColor + ".css'>");

    jQuery(".ColorChange").click(function () {
        var newColor = jQuery(this).attr("data-color");
        SetColorChangeCookie(newColor);
        $("#ColorChange").attr("href", "/css/cambio/" + newColor + ".css");
    });
}


function SetColorChangeCookie(val) {
    jQuery.cookie("colorchange", val, { path: '/', expires: 2 })
}

function GetColorChangeCookie() {
    var currentColor = jQuery.cookie("colorchange");
    if (currentColor != null) {
        return currentColor;
    }
    else {
        return "default";
    }
}



if (typeof (AfterConvertHermesContainerCallbacks) == 'undefined') {
    AfterConvertHermesContainerCallbacks = [];
}


function ShowFBLive(Embed) {
    var $parentDiv = $(".MainContentPlaceDiv:first");
    var $embedyoutube = jQuery("<div>",
        {
            id: "embedyoutube",
            style: "float: none; margin: 0 auto;",
            html: Embed
        }
    );

    $parentDiv.prepend($embedyoutube);
    var style = $embedyoutube.find("iframe")
        .width("100%")
        .attr("style") + ";display:block;margin: 0 auto;";
    $embedyoutube.find("iframe").attr("style", style);
    CreateModal($("body"), "Facebook LIVE", $embedyoutube, []
        , function ($modal) {
            $modal.find(".modal-dialog").removeClass("modal-md").addClass("modal-lg");
        }
        , function () {
            return false;
            //$embedyoutube.remove();
        }
        , true
        , function () {
            var deseaSalirFBLive = confirm("Esta seguro que desea salir de este FBLive?");
            if (deseaSalirFBLive) {
                jQuery.cookie("FBLiveClosed", true, { path: '/' });
            }
            return deseaSalirFBLive;
        });
}


AfterConvertHermesContainerCallbacks.push(function () {
    var FBLiveClosed = jQuery.cookie("FBLiveClosed");
    $.ajax({
        url: "/app_httphandlers/getexterno.ashx?key=fbLiveVideos",
        dataType: "json",
        success: function (data) {
            console.log("fbLiveVideos", data);
            if (data.length > 0 && data[0].Status == "LIVE") {
                if (!FBLiveClosed) {
                    ShowFBLive(data[0].Embed);
                }


                var $fbLiveButton = $("<span>", {
                    html: "<h1>FBLive</h1>",
                    click: function () {
                        ShowFBLive(data[0].Embed);
                    }
                });

                $(".ChatBtn").before($fbLiveButton);

            }
        }
    });
});;
// -----------------------------------
// 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);};}());
;
