﻿
function actionCustomFormatter (cellvalue, options, rowdata) {

        var l = options.colModel.link;
        return '<a href="/' + l.area + '/' + l.controller + '/' + l.action + '/' + options.rowId +
               '" rel="localize[' + l.lang + ']" >' + l.lang + '</a>';
}

function actionCustomFormatterJavascript(cellvalue, options, rowdata) {

    var l = options.colModel.link;
    return '<a href="javascript:void(0);" rel="localize[' + l.lang + ']" onclick="' + l.method + '(\''+ options.rowId + '\')" >' + l.lang + '</a>';
}

function adjustGrid(id) {
        /*Esto no está funcionando bien...*/
        /*$("table#" + id).setGridWidth($("table#" + id).parents(".ui-tabs-panel:first").width());*/
}

function focusWatermark(elementId, text) {
    var element = $('input#' + elementId); 
    if (element.val() == text) {
        element.val('');
        element.toggleClass('tbWaterMark');
    }
}

function blurWatermark(elementId, text) {
    var element = $('input#' + elementId);
    if (element.val() == '') {
        element.val(text);
        var selectedValueControlId = elementId + 'SelectedValue';
        var selectedValueControl = $('input:hidden#' + selectedValueControlId);
        if (selectedValueControl) {
            selectedValueControl.val(''); //Saco el valor seleccionado del hidden.
        }
        element.toggleClass('tbWaterMark');
    }
}

function filterNumeric(e) {
    
    if ([e.keyCode || e.which] == 9) //this is to allow tab
        return true;
    if ([e.keyCode || e.which] == 8) //this is to allow backspace
        return true;    
    if ([e.keyCode || e.which] < 48 || [e.keyCode || e.which] > 57)
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
}

function filterDecimal_allowsNegative(e) {
    if ([e.keyCode || e.which] == 39) //this is to allow right arrow
        return true;
    if ([e.keyCode || e.which] == 37) //this is to allow left arrow
        return true;
    if ([e.keyCode || e.which] == 9) //this is to allow tab
        return true;   
    if ([e.keyCode || e.which] == 8) //this is to allow backspace
        return true;
    if ([e.keyCode || e.which] == 46 || [e.keyCode || e.which] == 45) //Acepto punto y el - para números negativos
        return true;
    if ([e.keyCode || e.which] < 48 || [e.keyCode || e.which] > 57)
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
}

function getCursorSelection(textBox) {
    var pos = -1;
    var len = -1;
    if (document.selection) {
        //IE
        var range = document.selection.createRange();
        len = range.text.length;
        pos = Math.abs(range.moveStart("character", -1000000));
        return { pos: pos, len: len };
    } else {
        if (textBox.selectionStart != undefined && textBox.selectionEnd != undefined) {
            pos = textBox.selectionStart;
            len = textBox.selectionEnd - pos;
            return { pos: pos, len: len };
        }
    }
    return undefined;
}


function validateDecimal(ev) {
    var $target = $(ev.target);
    var val = $target.val();
    var point = val.indexOf('.', 0) != -1; //Hay punto?
    var i = point ? val.indexOf('.', 0) : val.length;
    var first = val.substr(0, i);    //Parte a la izquierda del punto
    var second = point ? val.substr(i + 1, val.length - i) : "";  //Parte a la derecha del punto
    var isValid = true;
    var cursorSelection = getCursorSelection(ev.target);
    if ($target.attr('scale') && $target.attr('prec') && (cursorSelection != undefined)) {
        if (cursorSelection.pos > first.length) {
            isValid = (second.length - cursorSelection.len < $target.attr('scale'));
        }
        isValid = isValid && ((first.length + second.length - cursorSelection.len) < $target.attr('prec')) &&
                !( cursorSelection.pos == val.indexOf('.', 0) && cursorSelection.len == 1) ;
    }

    return {
        point: point,
        first: first,
        second : second,
        prec: first.length + second.length,
        scale: second.length,
        isValid: isValid
    };
}

function filterDecimal(e) {

    if ([e.keyCode || e.which] == 39) //this is to allow right arrow
        return true;
    if ([e.keyCode || e.which] == 37) //this is to allow left arrow
        return true;
    if ([e.keyCode || e.which] == 9) //this is to allow tab
        return true;
    if ([e.keyCode || e.which] == 8) //this is to allow backspace
        return true;

    var $target = $(e.target);
    var dec = validateDecimal(e);
    if ([e.keyCode || e.which] == 46) { //Acepto punto (si no existe)
        if (dec.point) {
            e.preventDefault ? e.preventDefault() : e.returnValue = false;
        } else {
            return true;
        }
    }

    if ([e.keyCode || e.which] < 48 || [e.keyCode || e.which] > 57) {
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
    } else if (!dec.isValid) {
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
    }
}

/*
function filterDecimal(e) {

    if ([e.keyCode || e.which] == 9) //this is to allow tab
        return true;
    if ([e.keyCode || e.which] == 8) //this is to allow backspace
        return true;
    if ([e.keyCode || e.which] == 46) //Acepto punto
        return true;
    if ([e.keyCode || e.which] < 48 || [e.keyCode || e.which] > 57)
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
}*/



function filterAlfabetical(e, _object) {
    if ([e.keyCode || e.which] == 9) //this is to allow tab
        return true;
    if ([e.keyCode || e.which] == 8) //this is to allow backspace
        return true;

    if ([e.keyCode || e.which] < 65
    || ([e.keyCode || e.which] > 90 && [e.keyCode || e.which] < 97) 
    ||  [e.keyCode || e.which] > 122) {
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
    }


//    var letter = [e.keyCode || e.which];
//    if ([e.keyCode || e.which] >= 97 && [e.keyCode || e.which] <= 122) {
//        alert(String.fromCharCode(letter - 32));
//        _object.value = _object.value.toUpperCase();
//    }
    
}

function trace(s) {
    if (this.console && typeof console.log != "undefined") {
        console.log(s);
    }
}

function param() {
    this.array = new Array(1);

    this.setValue = function(v) { this.array[0] = v; }
    this.getValue = function() { return this.array[0]; }
}


//Fechas
function InicializeDatePickerMinMaxReference(datepickerId, asociatedMin, asociatedMax) {
    $("#" + datepickerId).datepicker({
        showOn: 'button',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        minDate: $("#" + asociatedMin).val(),
        maxDate: $("#" + asociatedMax).val(),
        hideIfNoPrevNext: true,
        buttonImage: '/Content/img/datepicker.gif',
        open: function () {
            $("#ui-datepicker-div").css("z-index", $(this).parent().css("z-index") + 1);
        }
    });
}

function InicializeDatePicker(datepickerId, asociated, limit) {
    InicializeDatePickerWithBeforeShowFunction(datepickerId, asociated, limit, null);
}

function InicializeDatePickerWithBeforeShowFunction(datepickerId, asociated, limit, beforeShowFunction) {
    $("#" + datepickerId).datepicker({
        showOn: 'button',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        minDate: '-1d',
        hideIfNoPrevNext: true,
        buttonImage: '/Content/img/datepicker.gif',
        onSelect: function (dateText, inst) {
            $("#" + asociated).datepicker('option', limit, dateText);
        },
        open: function () {
            $("#ui-datepicker-div").css("z-index", $(this).parent().css("z-index") + 1);
        },
        beforeShow: function (input, inst) {
            if (beforeShowFunction != null) {
                beforeShowFunction();
            }
        }
    });
}

function InicializeDatePickerNoMinDate(datepickerId, asociated, limit) {
    $("#" + datepickerId).datepicker({
        showOn: 'button',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',        
        hideIfNoPrevNext: true,
        buttonImage: '/Content/img/datepicker.gif',
        onSelect: function(dateText, inst) {
            $("#" + asociated).datepicker('option', limit, dateText);
        }
    });
}

function InicializeDatePickerNoMinMaxDate(datepickerId) {
    $("#" + datepickerId).datepicker({
        showOn: 'button',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        minDate: '-1d',
        hideIfNoPrevNext: true,
        buttonImage: '/Content/img/datepicker.gif'
        
    });
}


function typeDateFormat(value) {
    var val1 = /^[\d]?\d\D\D\D$/.test(value);
    var val2 = /^\d\d$/.test(value) || /^\d\d\d\d$/.test(value);
    var val4 = /^\d\d\d\d\d\d+/.test(value);
    var val3 = /^\d?\d[\/-]\d?\d[\/-]\d\d+/.test(value);
    var val5 = /^[\d]?\d\D\D\D\d\d+/.test(value);
    if (value == "") {
        return true;
    }
    else {
        return (val1 || val2 || val3 || val4 || val5);
    }
}

function typeIntFormat(value) {
    var val = /^\d+$/.test(value);
    return val;
}

function ParseDate(cId) {
    var typedDate = $("#" + cId).val();

    var day, month, year;
    if (typedDate != "") {
        if (typeDateFormat(typedDate)) {            

            day = $("#" + cId).datepicker('getDate').getDate();
            month = $("#" + cId).datepicker('getDate').getMonth() + 1;
            year = $("#" + cId).datepicker('getDate').getFullYear();
            $("#" + cId).val(day + "/" + month + "/" + year);
            day = ""; month = ""; year = "";          
        }
        else {
            trace("Formato incorrecto: " + typedDate);
            $("#" + cId).val("");
        }
    }
}

function initJqGridData(gridId, keyName, data, sortName, sortOrder) {
    var $table = $('#' + gridId);
    
    var sort_order = sortOrder;
    if (!sort_order) {
        sort_order = "asc";
    }
    
    if (!sortName) {
        sortName = $table.getGridParam("sortname");
    }
    $.each(data, function() {
        var result = $table.addRowData(this[keyName], this);
    });

    $table.setGridParam({ sortname: sortName, sortorder: sort_order }).trigger('reloadGrid');
}

function addJqGridPostData(gridId, formId, dataPrefix, colNames) {
    //creo un contenedor para los inputs
    var divClass = "jqGridPostData-" + gridId;
    var $container = $('#' + formId + " ." + divClass);
    if ($container.length == 0) {
        $container = $("<div />").hide().addClass(divClass).appendTo($('#' + formId));
    }
    $container.html('');

    //agrego los inputs
    var $table = $('#' + gridId);
    var tableIDs = $table.getDataIDs();
    var i = 0;
    $.each(tableIDs, function() {
        var rowData = $table.getRowData(this);
        var pre = dataPrefix + "[" + i + "].";
        $.each(colNames, function() {
            var name = pre + this;
            $container.append($("<input type='hidden'/>").attr('name', name).attr('value', rowData[this]));
        });
        i++;
    });
}


    function collapseSingle(id) {
        $("#" + id).hide();
        $("#" + id.replace('table_', 'exp_')).show();
        $("#" + id.replace('table_', 'coll_')).hide();
    }

    function expandSingle(id) {
        $("#" + id).show();
        $("#" + id.replace('table_', 'coll_')).show();
        $("#" + id.replace('table_', 'exp_')).hide();
    }

    function collapse() {
        $("[type=collapse]").hide();
        $("[type=collapseBtn]").hide();
        $("[type=expandBtn]").show();
    }
    function expand() {
        $("[type=collapse]").show();
        $("[type=collapseBtn]").show();
        $("[type=expandBtn]").hide();
    }

    
; (function ($) {
    
    
    $.extend($.datepicker, {
        
        awParseDate: function (format, value, settings) {
            //trace('AWParse: Recibo ' + value);
            if (format == null || value == null)
                throw 'Invalid arguments';
            value = (typeof value == 'object' ? value.toString() : value + '');
            if (value == '')
                return null;
            var returnDate = new Date();
            var myDate = new Date();
            var currentDate = (myDate.getMonth() + 1) + '/' + myDate.getDay() + '/' + myDate.getFullYear();

            if (value.length == 0) return;
            var s = value.replace(/\s/g, '');
            s = s.replace('.', '');
            s = s.replace('.', '');
            var day = 0;
            var month = '';
            var year = 0;
            var monthIndex = -1;
            var today = new Date();
            if (s.match(/^\d\d$/)) {
                if (today.getMonth() < 9) s += '0';
                s += (today.getMonth() + 1);
            }

            if (s.match(/^\d\d\d\d$/)) {
                s += today.getFullYear();
            }
            if (s.match(/^\d\d\d\d\d\d+/)) {
                day = parseInt(s.substring(0, 2), 10);
                monthIndex = parseInt(s.substring(2, 4), 10) - 1;
                year = s.substring(4);
            }
            if (s.match(/^[\d]?\d\D\D\D$/)) {
                s += today.getFullYear();
            }
            if (s.match(/^[\d]?\d\D\D\D\d\d+/)) {
                var index = s.search(/\D/);
                day = parseInt(s.substring(0, index), 10);
                month = s.substring(index, index + 3);
                year = parseInt(s.substring(index + 3), 10);

            }
            if (s.match(/^\d?\d[\/-]\d?\d[\/-]\d\d+/)) {
                var index = s.search(/[\/-]/);
                day = parseInt(s.substring(0, index), 10);
                var index2 = s.search(/[\/-]\d+$/);
                monthIndex = parseInt(s.substring(index + 1, index2) - 1, 10);
                year = parseInt(s.substring(index2 + 1), 10);
            }

            if (year < 100) {
                year = year > 39 ? parseInt(year, 10) + 1900 : parseInt(year, 10) + 2000;
            }

            var err = 0;
            //   /* Validation leap-year / february / day */
            var leap = 0;

            if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
                leap = 1;
            }
            if ((monthIndex == 2) && (leap == 1) && (day > 29)) {
                err = 23;
                trace('Error: ' + err);
            }
            if ((monthIndex == 2) && (leap != 1) && (day > 28)) {
                err = 24;
                trace('Error: ' + err);
            }
            /* Validation of other months */
            if ((day > 31) && ((monthIndex == 1) || (monthIndex == 3) || (monthIndex == 5) || (monthIndex == 7) || (monthIndex == 8) || (monthIndex == 10) || (monthIndex == 12))) {
                err = 25;
                trace('Error: ' + err);
            }
            if ((day > 30) && ((monthIndex == 4) || (monthIndex == 6) || (monthIndex == 9) || (monthIndex == 11))) {
                err = 26;
                trace('Error: ' + err);
            }

            var returnDateString = (monthIndex + 1) < 10 ? day + '/0' + (monthIndex + 1) + '/' + year : day + '/' + (monthIndex + 1) + '/' + year;
            //trace('AWParse: Devuelvo '+ returnDateString);

            return returnDateString;
        },
        _setDateFromField: function (inst, noDefault) {
            if (inst.input.val() == inst.lastVal) {
                return;
            }
            var dateFormat = this._get(inst, 'dateFormat');
            var dates = inst.lastVal = inst.input ? inst.input.val() : null;
            var date, defaultDate;
            date = defaultDate = this._getDefaultDate(inst);
            var settings = this._getFormatConfig(inst);
            try {
                var date2 = this.awParseDate(dateFormat, dates, settings)
                date = this.parseDate(dateFormat, date2, settings) || defaultDate;
            } catch (event) {
                this.log(event);
                dates = (noDefault ? '' : dates);
            }
            inst.selectedDay = date.getDate();
            inst.drawMonth = inst.selectedMonth = date.getMonth();
            inst.drawYear = inst.selectedYear = date.getFullYear();
            inst.currentDay = (dates ? date.getDate() : 0);
            inst.currentMonth = (dates ? date.getMonth() : 0);
            inst.currentYear = (dates ? date.getFullYear() : 0);
            this._adjustInstDate(inst);
        }

        })       
    })(jQuery);
