﻿(function(jQuery) {
    jQuery.fn.checkFormats = function(options) {
        var defaults = {
            Extension: '', // Extension a validar.
            Message: '', // Mensaje a mostrar en caso no se cumpla ningún formato.
            Control: null // Control a resaltar cuando no se cumpla ningún formato.
        };
        var options = jQuery.extend({}, defaults, options);
        var blnFormat = true;
        var strFormat = jQuery.trim($(this).val());
        this.each(function() {
            blnFormat = (strFormat.toLowerCase().indexOf(options.Extension.toLowerCase()) >= 0 ? true : false);
            if (!blnFormat) {
                if (options.Control != null) { options.Control.addClass('ui-state-error') };
                if (options.Message != '') {
                    alert(options.Message);
                };
                if (options.Control != null) { options.Control.focus() };
            } else {
                if (options.Control != null) { options.Control.removeClass('ui-state-error') };
            };
        });
        return blnFormat;
    };

    jQuery.fn.DataSource = function(options) {
        var defaults = {
            Value: '', // Valor a mostrar después de cargar el contenido.
            Source: [], // Origen de Datos
            ValueName: '', // códigos de valores de la lista
            DisplayName: '', // Nombres de valores de la lista
            OptionalValue: true // Incluye el item (Seleccione) en la lista.
        };
        var options = jQuery.extend({}, defaults, options);
        var strValue = '';
        this.each(function() {
            strValue = (options.Value == '') ? jQuery.trim($(this).val()) : options.Value;
            $(this).html('');
            if (options.Source != '') {
                if (options.OptionalValue) {
                    $(this).append($("<option></option>").attr("value", "").text("(Seleccione)"));
                }
                for (i = 0; i < options.Source.length; i++) {
                    $(this).append($("<option></option>").attr("value", eval('options.Source[' + i + '].' + options.ValueName)).text(eval('options.Source[' + i + '].' + options.DisplayName)));
                }
            }
            $(this).val(strValue);
        });
        return true;
    };

    jQuery.fn.checkDate = function(options) {
        var defaults = {
            Date: '',
            Message: '',
            Controls: []
        };
        var options = jQuery.extend({}, defaults, options);
        var days = 0;
        var blnDate = true;
        this.each(function() {
            //$(this).val(options.Message);
            // Verifica fecha ingresada
            blnDate = checkDate($(this));
            // Compara fechas
            if (options.Date != '' && blnDate == true) {
                days = DaysDiff($(this).val(), options.Date);
                if (days > 0) {
                    blnDate = false;
                    $(this).addClass('ui-state-error');
                    for (i = 0; i < options.Controls.length; i++) {
                        options.Controls[i].addClass('ui-state-error');
                    };
                    if (options.Message == '') { options.Message = 'La fecha ingresada no puede ser mayor a la actual.'; };
                    alert(options.Message);
                    $(this).focus();
                } else {
                    blnDate = true;
                    $(this).removeClass('ui-state-error');
                    for (i = 0; i < options.Controls.length; i++) {
                        options.Controls[i].removeClass('ui-state-error');
                    };
                }
            };
        });
        return blnDate;
    };

    jQuery.fn.checkSelect = function(options) {
        var defaults = {
            Value: '',
            Message: '',
            Controls: [],
            ValueCero: true
        };
        var options = jQuery.extend({}, defaults, options);
        var blnSelect = true;
        this.each(function() {
            if (options.Value != '') {
                if ($(this).val() != options.Value) {
                    $(this).addClass('ui-state-error');
                    alert(options.Message);
                    $(this).focus();
                    blnSelect = false;
                } else {
                    $(this).removeClass('ui-state-error');
                    blnSelect = true;
                };
            } else {
                if (options.ValueCero) {
                    if ($(this).val() == '' || $(this).val() == null || $(this).val() == '0') {
                        $(this).addClass('ui-state-error');
                        alert(options.Message);
                        $(this).focus();
                        blnSelect = false;
                    } else {
                        $(this).removeClass('ui-state-error');
                        blnSelect = true;
                    };
                } else {
                    if ($(this).val() == '' || $(this).val() == null) {
                        $(this).addClass('ui-state-error');
                        alert(options.Message);
                        $(this).focus();
                        blnSelect = false;
                    } else {
                        $(this).removeClass('ui-state-error');
                        blnSelect = true;
                    };
                }
            };
        });
        return blnSelect;
    };

    jQuery.fn.checkText = function(options) {
        var defaults = {
            Value: '', // Compara con el valor del control.
            Message: '', // Mensaje a mostrar.
            Controls: [], // Controles a incluir en la validación
            Operator: 'And', // Operador de validación de controles
            Control: null, // Control que indica la obligatoriedad del principal, sólo cuando este tenga un valor.
            CssClass: true
        };
        var options = jQuery.extend({}, defaults, options);
        var blnText = true;
        var strValue = jQuery.trim($(this).val());
        this.each(function() {
            blnText = strValue == options.Value ? false : true;
            for (i = 0; i < options.Controls.length; i++) {
                if (options.Operator == 'And') {
                    blnText = (blnText) && (jQuery.trim(options.Controls[i].val()) == options.Value ? false : true);
                } else {
                    blnText = (blnText) || (jQuery.trim(options.Controls[i].val()) == options.Value ? false : true);
                };
            };
            if (!blnText) {
                if (options.CssClass) {
                    (options.Control == null) ? $(this).addClass('ui-state-error') : options.Control.addClass('ui-state-error');
                    for (i = 0; i < options.Controls.length; i++) {
                        options.Controls[i].addClass('ui-state-error');
                    };
                };
                if (options.Message != '') {
                    alert(options.Message);
                };
                (options.Control == null) ? $(this).focus() : options.Control.focus();
            } else {
                (options.Control == null) ? $(this).removeClass('ui-state-error') : options.Control.removeClass('ui-state-error');
                for (i = 0; i < options.Controls.length; i++) {
                    options.Controls[i].removeClass('ui-state-error');
                };
            };
        });
        return blnText;
    };

    jQuery.fn.ShowCss = function(options) {
        var defaults = {
            Message: '', // Mensaje a mostrar.
            Controls: [], // Controles a incluir en la validación
            CssClass: true,
            Focus: null
        };
        var options = jQuery.extend({}, defaults, options);
        var blnText = true;
        this.each(function() {
            if (options.CssClass) {
                $(this).addClass('ui-state-error');
                for (i = 0; i < options.Controls.length; i++) {
                    options.Controls[i].addClass('ui-state-error');
                };
                if (options.Message != '') {
                    alert(options.Message);
                };
                (options.Focus == null) ? $(this).focus() : options.Focus.focus();
            } else {
                $(this).removeClass('ui-state-error');
                for (i = 0; i < options.Controls.length; i++) {
                    options.Controls[i].removeClass('ui-state-error');
                };
            };
        });
        return blnText;
    };

    jQuery.fn.checkControl = function(options) {
        var defaults = {
            Value: '', // Compara con el valor del control.
            Message: '', // Mensaje a mostrar.
            Controls: [], // Controles a incluir en la validación
            Operator: 'And', // Operador de validación de controles
            Control: null // Control que indica la obligatoriedad del principal, sólo cuando este tenga un valor.
        };
        var options = jQuery.extend({}, defaults, options);
        var blnText = true;
        var strValue = jQuery.trim($(this).val());
        this.each(function() {
            blnText = (options.Control == null ? false : true);
            if (blnText) {
                if (jQuery.trim(options.Control.val()) != options.Value) {
                    blnText = (strValue == '' ? false : true);
                };
            };
            if (!blnText) {
                $(this).addClass('ui-state-error');
                if (options.Control != null) { options.Control.addClass('ui-state-error') };
                for (i = 0; i < options.Controls.length; i++) {
                    options.Controls[i].addClass('ui-state-error');
                };
                if (options.Message != '') {
                    alert(options.Message);
                };
                $(this).focus();
            } else {
                $(this).removeClass('ui-state-error');
                if (options.Control != null) { options.Control.removeClass('ui-state-error') };
                for (i = 0; i < options.Controls.length; i++) {
                    options.Controls[i].removeClass('ui-state-error');
                };
            };
        });
        return blnText;
    };

    jQuery.fn.checkLength = function(options) {
        var defaults = {
            Value: '',
            Message: '',
            MinLength: null,
            MaxLength: null,
            Control: null,
            Mandatory: true
        };
        var options = jQuery.extend({}, defaults, options);
        var blnText = true;
        var strValue = jQuery.trim($(this).val());
        this.each(function() {
            if (options.Mandatory) {
                blnText = strValue == options.Value ? false : true;
            };
            if (strValue.length > 0) {
                if (options.MinLength != null && options.MaxLength != null) {
                    blnText = (strValue.length < options.MinLength && strValue.length > options.MaxLength ? false : true);
                } else if (options.MinLength != null) {
                    blnText = (strValue.length < options.MinLength ? false : true);
                } else if (options.MaxLength != null) {
                    blnText = (strValue.length > options.MaxLength ? false : true);
                }
            };
            if (!blnText) {
                (options.Control == null) ? $(this).addClass('ui-state-error') : options.Control.addClass('ui-state-error');
                if (options.Message != '') {
                    alert(options.Message);
                };
                (options.Control == null) ? $(this).focus() : options.Control.focus();
            } else {
                (options.Control == null) ? $(this).removeClass('ui-state-error') : options.Control.removeClass('ui-state-error');
            };
        });
        return blnText;
    };

    // Función para comparar controles
    // Devuelve True: si el control principal es igual a los otros controles.
    // Devuelve False: si el control principal es diferente a alguno de los otros controles.
    jQuery.fn.Compare = function(options) {
        var defaults = {
            Value: '',
            Message: '',
            Controls: [],
            Operator: '==' // ('==': iguales, '!=': diferentes)
        };
        var options = jQuery.extend({}, defaults, options);
        var blnCompare = true;
        this.each(function() {
            blnCompare = options.Controls.length <= 0 ? false : true;
            for (i = 0; i < options.Controls.length; i++) {
                if (options.Operator == '==') {
                    blnCompare = (blnCompare) && (jQuery.trim($(this).val()) == jQuery.trim(options.Controls[i].val()) ? true : false);
                } else {
                    blnCompare = (blnCompare) && (jQuery.trim($(this).val()) == jQuery.trim(options.Controls[i].val()) ? false : true);
                }
            };
            if (!blnCompare) {
                $(this).addClass('ui-state-error');
                for (i = 0; i < options.Controls.length; i++) {
                    options.Controls[i].addClass('ui-state-error');
                };
                if (options.Message != '') {
                    alert(options.Message);
                };
                $(this).focus();
            } else {
                $(this).removeClass('ui-state-error');
                for (i = 0; i < options.Controls.length; i++) {
                    options.Controls[i].removeClass('ui-state-error');
                };
            };
        });
        return blnCompare;
    };

    jQuery.fn.ReadOnly = function(options) {
        var defaults = {
            Value: true
        };
        var options = jQuery.extend({}, defaults, options);
        this.each(function() {
            var type = $(this).attr("type");
            if (type == 'text') {
                if (options.Value) {
                    $(this).attr('readonly', 'readonly');
                    $(this).addClass('Deshabilitado');
                } else {
                    $(this).attr('readonly', '');
                    $(this).removeClass('Deshabilitado');
                };
            } else {
                if (options.Value) {
                    $(this).attr('disabled', 'disabled');
                    $(this).addClass('Deshabilitado');
                } else {
                    $(this).attr('disabled', '');
                    $(this).removeClass('Deshabilitado');
                };
            };
        });
    };

    jQuery.fn.CheckEmail = function(options) {
        var defaults = {
            Requiered: false,
            Message: ''
        };
        var options = jQuery.extend({}, defaults, options);
        var blnEmail = true;
        this.each(function() {
            if (options.Requiered) {
                blnEmail = (jQuery.trim($(this).val()) != '') ? true : false;
            };
            if (jQuery.trim($(this).val()) != '') {
                if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(jQuery.trim($(this).val()))) {
                    blnEmail = true;
                }
                else {
                    blnEmail = false;
                };
            };
            if (!blnEmail) {
                $(this).addClass('ui-state-error');
                if (options.Message != '') { alert(options.Message); };
                $(this).focus();
            } else {
                $(this).removeClass('ui-state-error');
            };
        });
        return blnEmail;
    };

    jQuery.fn.checkVal = function(options) {
        var defaults = {
            Message: '',
            MinValue: null,
            MaxValue: null
        };
        var options = jQuery.extend({}, defaults, options);
        var blnVal = true;
        var value = 0;
        this.each(function() {
            value = Number($(this).val());
            blnVal = (value >= options.MinValue) && (value <= options.MaxValue);
            if (!blnVal) {
                $(this).addClass('ui-state-error');
                if (options.Message != '') { alert(options.Message); };
                $(this).focus();
            } else {
                $(this).removeClass('ui-state-error');
            };
        });
        return blnVal;
    };

    jQuery.fn.checkValues = function(options) {
        var defaults = {
            Value: '', // Compara con el valor del control principal.
            Message: '', // Mensaje a mostrar.
            Controls: [, 2], // Controles a validar con su correspondiente valor de comparacion (valores: '==','!=')
            Operator: 'And', // Operador de validación de controles ('And': Todos los controles cumplen la condición, 'Or': cualquier control cumple la condicion)
            Focus: null, // Control a enfocar al devorvel el valor false.
            Compare: '==', // tipo de comparación del control principal con el valor por defecto ('==':igual, '!=': diferente)
            CssClass: true,
            CssExclude: []
        };
        var options = jQuery.extend({}, defaults, options);
        var blnText = true;
        var blnExclude = false;
        this.each(function() {
            if (options.Compare == '==') {
                blnText = (jQuery.trim($(this).val()) == options.Value ? true : false);
            } else {
                blnText = (jQuery.trim($(this).val()) != options.Value ? true : false);
            }
            for (i = 0; i < options.Controls.length; i++) {
                var strControl = jQuery.trim(options.Controls[i][0].val());
                if (options.Controls[i][1] == '==') {
                    if (options.Operator == 'And') {
                        blnText = blnText && (strControl == options.Value ? true : false);
                    } else {
                        blnText = blnText || (strControl == options.Value ? true : false);
                    }
                } else {
                    if (options.Operator == 'And') {
                        blnText = blnText && (strControl != options.Value ? true : false);
                    } else {
                        blnText = blnText || (strControl != options.Value ? true : false);
                    }
                }
            };
            if (blnText) {
                for (i = 0; i < options.CssExclude.length; i++) {
                    if (options.CssExclude[i].attr('id') == $(this).attr('id')) {
                        blnExclude = true;
                        break;
                    };
                };
                if (!blnExclude && options.CssClass) { $(this).addClass('ui-state-error'); };
                for (i = 0; i < options.Controls.length; i++) {
                    blnExclude = false;
                    for (j = 0; j < options.CssExclude.length; j++) {
                        if (options.CssExclude[j].attr('id') == options.Controls[i][0].attr('id')) {
                            blnExclude = true;
                            break;
                        };
                    };
                    if (!blnExclude && options.CssClass) { options.Controls[i][0].addClass('ui-state-error'); };
                };
                if (options.Message != '') {
                    alert(options.Message);
                };
                (options.Focus == null) ? $(this).focus() : options.Focus.focus();
            } else {
                $(this).removeClass('ui-state-error');
                if (options.Control != null) { options.Control.removeClass('ui-state-error') };
                for (i = 0; i < options.Controls.length; i++) {
                    options.Controls[i][0].removeClass('ui-state-error');
                };
            };
        });
        return blnText;
    };

    $.fn.ValidDId = function(options) {
        var defaults = {
            Length: 12,
            Pattern: /[1234567890]/,
            Control: null
        };
        var options = $.extend({}, defaults, options);
        this.each(function() {
            if (event.keyCode == 8) { return true; };
            $(this).keypress(function(e) {
                return $.fn.ValidDId.lengthDId(e, $(this).val(), options);
            });
        });
    };
    $.fn.ValidDId.alowKeys = function(event, strValue, intChars) {
        if (strValue.length >= intChars) {
            if (event.preventDefault) event.preventDefault();
            else event.returnValue = false;
            return false;
        }
    }
    $.fn.ValidDId.lengthDId = function(event, strValue, options) {
        var blnValid = false;
        var strPattern = /[a-zA-ZÑñ1234567890@.-_áéíóú;:()+*!"·$%& ]/;
        switch (options.Control.val()) {
            case "0": // Sin Documento
                $.fn.ValidDId.alowKeys(event, strValue, 0);
                return options.Pattern.test(String.fromCharCode(event.keyCode));
                break;
            case "1": // RUC
                $.fn.ValidDId.alowKeys(event, strValue, 11);
                return options.Pattern.test(String.fromCharCode(event.keyCode));
                break;
            case "2": // DNI/Libreta Electoral
                $.fn.ValidDId.alowKeys(event, strValue, 8);
                return options.Pattern.test(String.fromCharCode(event.keyCode));
                break;
            case "3": // Carne de Identidad
                $.fn.ValidDId.alowKeys(event, strValue, 12);
                options.Pattern = strPattern;
                return options.Pattern.test(String.fromCharCode(event.keyCode));
                break;
            case "4": // Carne de Extranjeria
                $.fn.ValidDId.alowKeys(event, strValue, 12);
                options.Pattern = strPattern;
                return options.Pattern.test(String.fromCharCode(event.keyCode));
                break;
            case "5": // Pasaporte
                $.fn.ValidDId.alowKeys(event, strValue, 10);
                options.Pattern = strPattern;
                return options.Pattern.test(String.fromCharCode(event.keyCode));
                break;
            case "8": // Otros
                $.fn.ValidDId.alowKeys(event, strValue, 10);
                options.Pattern = strPattern;
                return options.Pattern.test(String.fromCharCode(event.keyCode));
                break;
            case "99": // Código SAT
                $.fn.ValidDId.alowKeys(event, strValue, 10);
                return options.Pattern.test(String.fromCharCode(event.keyCode));
                break;
            default:
                $.fn.ValidDId.alowKeys(event, strValue, options.Length);
                options.Pattern = strPattern;
                return options.Pattern.test(String.fromCharCode(event.keyCode));
                break;
        }
        return blnValid;
    }

    jQuery.fn.ControlsDId = function(options) {
        var defaults = {
            Controls: [],
            ChangeValue: true
        };
        var options = jQuery.extend({}, defaults, options);
        var blnControls = true;

        this.each(function() {
            if (options.Controls.length >= 4) {
                options.Controls[0].ReadOnly({ Value: false });
                options.Controls[1].ReadOnly({ Value: false });
                options.Controls[2].ReadOnly({ Value: false });
                options.Controls[3].ReadOnly({ Value: false });
                options.Controls[4].ReadOnly({ Value: false });
                if (options.ChangeValue == true) {
                    options.Controls[0].val('');
                    options.Controls[1].val('');
                    options.Controls[2].val('');
                    options.Controls[3].val('');
                    options.Controls[4].val('');
                }
                if ($(this).val() == 0) {
                    options.Controls[0].ReadOnly();
                    options.Controls[1].ReadOnly({ Value: false });
                    options.Controls[2].ReadOnly({ Value: false });
                    options.Controls[3].ReadOnly({ Value: false });
                    options.Controls[4].ReadOnly();
                } else if ($(this).val() == 1) {
                    options.Controls[0].ReadOnly({ Value: false });
                    options.Controls[1].ReadOnly();
                    options.Controls[2].ReadOnly();
                    options.Controls[3].ReadOnly();
                    options.Controls[4].ReadOnly({ Value: false });
                } else if ($(this).val() > 1) {
                    options.Controls[0].ReadOnly({ Value: false });
                    options.Controls[1].ReadOnly({ Value: false });
                    options.Controls[2].ReadOnly({ Value: false });
                    options.Controls[3].ReadOnly({ Value: false });
                    options.Controls[4].ReadOnly();
                }
            }
        });
        return blnControls;
    };

    /*jQuery.alowKeys = function(e, objControl, maxChars) {
    if (objControl.val().length >= maxChars) {
    if (e.preventDefault) e.preventDefault();
    else event.returnValue = false;
    return false;
    }
    }*/

    jQuery.HtmlToString = function(Text) {
        var regexp = /(<([^>]+)>)/ig;
        var strHtml = '';
        strHtml = Text.replace(regexp, '');
        strHtml = strHtml.replace('&nbsp;', '');
        return strHtml;
    }

    jQuery.GetHtmlEditor = function(Obj) {
        return $find(Obj);
    }

    jQuery.FormatNumber = function(nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }

    jQuery.ChildNodes = function(Obj, item, value) {
        var result;
        if (Obj.cells[item].childNodes.length > 0) {
            result = Obj.cells[item].childNodes.item(0).nodeValue;
        } else {
            result = value;
        }
        return result;
    }

    function DaysDiff(first, second) {
        var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
        var firstDate = parseDate(first);
        var secondDate = parseDate(second);

        var diffDays = ((firstDate.getTime() - secondDate.getTime()) / (oneDay));
        return diffDays;
    };

    function parseDate(str) {
        var date = str.split('/');
        return new Date(date[2], (date[1] - 1), date[0]);
    };

    function checkDate(obj) {
        var strFecha = obj.val();
        if (strFecha != undefined && strFecha.value != "") {
            if (!/^\d{2}\/\d{2}\/\d{4}$/.test(strFecha)) {
                obj.addClass('ui-state-error');
                alert("El formato de fecha no es válido, ingrese con el siguiente formato (dd/mm/aaaa).");
                obj.focus();
                return false;
            }
            var dia = parseInt(strFecha.substring(0, 2), 10);
            var mes = parseInt(strFecha.substring(3, 5), 10);
            var anio = parseInt(strFecha.substring(6), 10);
            switch (mes) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    numDias = 31;
                    break;
                case 4: case 6: case 9: case 11:
                    numDias = 30;
                    break;
                case 2:
                    if (checkBisisesto(anio)) { numDias = 29 } else { numDias = 28 };
                    break;
                default:
                    obj.addClass('ui-state-error');
                    alert("La fecha ingresada es erróonea.");
                    obj.focus();
                    return false;
            }
            if (dia > numDias || dia == 0) {
                obj.addClass('ui-state-error');
                alert("La fecha ingresada es errónea.");
                obj.focus();
                return false;
            }
            obj.removeClass('ui-state-error');
            return true;
        }
    }

    function checkBisisesto(anio) {
        if ((anio % 100 != 0) && ((anio % 4 == 0) || (anio % 400 == 0))) {
            return true;
        }
        else {
            return false;
        }
    }

})(jQuery);
