var objMainTab =
{
    typeClassOld: '',
    showMenuContent: function(pars, typeClass, url)
    {

        if (this.typeClassOld != "")
        {
            var o_elements = $("td[type='maintTab_" + this.typeClassOld + "']");

            $(o_elements[0]).removeClass('mnuActivoIzq');
            $(o_elements[1]).removeClass('mnuActivoTxt');
            $(o_elements[2]).removeClass('mnuActivoDer');

            $(o_elements[0]).addClass('mnuInactivoIzq');
            $(o_elements[1]).addClass('mnuInactivoTxt');
            $(o_elements[2]).addClass('mnuInactivoDer');
        }

        this.typeClassOld = typeClass;

        var o_elements = $("td[type='maintTab_" + typeClass + "']");

        $( o_elements[0] ).removeClass('mnuInactivoIzq');
        $( o_elements[1] ).removeClass('mnuInactivoTxt');
        $( o_elements[2] ).removeClass('mnuInactivoDer');

        $( o_elements[0] ).addClass('mnuActivoIzq');
        $( o_elements[1] ).addClass('mnuActivoTxt');
        $( o_elements[2] ).addClass('mnuActivoDer');

        document.getElementById('contentMenu').innerHTML = document.getElementById('messageLoadMenu').innerHTML;
        //console.log(url);

        $.ajaxSetup
                    (
                        {
                            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                            beforeSend: function( jqXHR ) 
                            {
                                jqXHR.overrideMimeType( 'application/x-www-form-urlencoded; charset=utf-8' );
                            }
                        }
                   );
        var o_pars = { "taskId": pars };

        $o_elm = $( "#contentMenu" );
        $o_elm.load
                    (
                        url,
                        o_pars,
                        function( response, status, xhr )
                        {
                            if (status == "error")
                            {
                                var msg = "Sorry but there was an error: ";
                                //alert( msg + xhr.status + " " + xhr.statusText );
                                console.log( msg + xhr.status + " " + xhr.statusText );
                            }
                            objMainTab.showMenu();
                        }
                    );
    },
    showMenu: function()
    {
        //document.getElementById('contentImg').innerHTML = document.getElementById( 'showMenu' ).innerHTML;
        document.getElementById('contentImg').innerHTML = "<img src='/images/common/btnOcultar.gif' width='7' height='25' style='cursor:pointer;' onClick='objMainTab.hideMenu()'><img src='/images/common/spacer.gif' width='5' height='5'>";
        $( "#contentMenu" ).show( "slide", {}, 500 );
    },
    hideMenu: function()
    {
        document.getElementById('contentImg').innerHTML = "<img src='/images/common/btnMostrar.gif' width='7' height='25' style='cursor:pointer;' onClick='objMainTab.showMenu()'><img src='/images/common/spacer.gif' width='5' height='5'>";
        //document.getElementById('contentImg').innerHTML = document.getElementById( 'hideMenu' ).innerHTML;
        $( "#contentMenu" ).hide( "slide", {}, 500 );
    },
    reqBody: function( url, block ) 
    {
        pars = "?block=" + block;
        document.getElementById('contentResultxx').src = ( url + pars );
    },
    modalDialog: function( url, param, originalRequest )
    {
        var options = $.extend
                                (
                                    {
                                        width       : 600,
                                        height      : 400,
                                        iframe      : url,
                                        fixed       : false,
                                        maskid      : 'bluemask',
                                        maskopacity : 40
                                    }, 
                                    param
                                );
        TINY.box.show( options );
    },
    windowsCloseAll: function()
    {
        TINY.box.hide();
    },
    modalUIDialog: function( elm, o_param )
    {
        var o_options = $.extend
                                (
                                    {
                                        title   : "",
                                        autoOpen: false,
                                        modal   : false,
                                        width   : 900,
                                        height  : 390,
                                        open    : function( ev, ui )
                                        {
                                            console.log( ev );
                                            console.log( ui );
                                        }
                                    },
                                    o_param
                                );
        $( elm ).dialog
        (
            o_options
        );
    }
};

pr = function( param )
{
    console.log( param );
}

var scrollFunction = function( idCTion )
{
    $( ".scrollTable" ).each
    ( 
        function( i )
        {
            console.log( i + " + " + this.id );
            if( this.id != "contentProcMenu_" + idCTion )
            {
                if( this.style.display == "block" || this.style.display == "" )
                {
                    console.log( i + " + " + "contentProcMenu_" + idCTion );
                    $(this).toggle( "slide", { direction: "up" }, 100 );
                }
            }
        }
    );
    $( "#contentProcMenu_" + idCTion ).toggle( "slide", { direction: "up" }, 100 );
    return false;
};
/***************************************************************************************************************/
redondear = function( cantidad, decimales )
{
    if( cantidad )
    {
        var cantidad = parseFloat( cantidad );
        var decimales = parseFloat( decimales );
        decimales = ( !decimales ? 2 : decimales );
        return Math.round( cantidad * Math.pow( 10, decimales ) ) / Math.pow( 10, decimales );
    }
    return 0;
}

String.prototype.trim = function()
{
    var retorno = this.replace( /^\s+/g, "" );
    retorno = retorno.replace( /\s+$/g, "" );
    return retorno;
};
/***************************************************************************************************************/
//UTIL PARA ORDENAR OPTION DEL SELECT DESPUES DE CARGARLOS POR AJAX
ordernarSelect = function( id_elm )
{
    var options = $( '#' + id_elm + ' option' );
    var arr = options.map
                (
                    function( _, o ) 
                    {
                        return { t: $( o ).text(), v: o.value };
                    }
                ).get();
    arr.sort
    (
        function( o1, o2 ) 
        {
            return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
        }
    );
    options.each
    (
        function( i, o ) 
        {
            console.log( i );
            o.value = arr[i].v;
            $( o ).text( arr[i].t );
        }
    );
};
///////////////////////////////////////////////////////
updateElementOption = function( s_NameSelect, data, control )
{
    if( control )
    {
        $( "#" + s_NameSelect ).empty();
        $( "#" + s_NameSelect ).append( "<option value=''> - Seleccione - </option>" );
    }
    $.each
            (
                data, function( index, item )
                {
                    $( "#" + s_NameSelect ).append( "<option value=" + index + ">" + item + "</option>" );
                }
            );
};
publicForSelectAjaxJSON = function( s_URL, o_Param, s_NameSelect, function_pr, add_opt )
{
    var control = false;
    if ( typeof( add_opt ) == 'undefined' )
    {
        control = true; 
    }
    else
    {
        control = add_opt; 
    }
    $.getJSON
            (
                s_URL, o_Param, function( data )
                {
                    updateElementOption( s_NameSelect, data, control );
                    if( typeof( function_pr ) == "function" )
                    {
                        function_pr( data );
                    }
                }
            );
};
updateElementFromJSON = function( s_URL, o_Param, s_NameElement )
{
    $.getJSON
            (
                s_URL, o_Param, function( data )
                {
                    switch ( $( "#" + s_NameElement )[0].tagName ) 
                    {
                        case 'INPUT'   :
                            $( "#" + s_NameElement ).val( data.value );
                        break;
                    }
                }
            );
};
/***************************************************************************************************************/
executeAjaxUpdater = function ( element, url, str, function_pr )
{
    $o_elm = $( "#" + element );
    $o_elm.load
            (
                    url,
                    str,
                    function ( response, status, xhr )
                    {
                        //console.log( typeof( function_pr ) );
                        if ( status == "error" )
                        {
                            var msg = "Sorry but there was an error: ";
                            //alert( msg + xhr.status + " " + xhr.statusText );
                            console.log( msg + xhr.status + " " + xhr.statusText );
                            return false;
                        }
                        if( typeof( function_pr ) == "function" )
                        {
                            function_pr( response );
                        }
                    }
            );
}
/***************************************************************************************************************/
executeAjaxJson = function( s_URL, o_Param, function_pr )
{
    //$.getJSON
    $.post
    (
        s_URL, o_Param, function( data )
        {
            //pr( data );
            try 
            {
                var param = jQuery.parseJSON( data );
                data = param;
            }
            catch ( err ) 
            {
                var param = "";
            }
            
            if( typeof data != 'object' )
            {
                data = data.replace( "<pre>", "" );
                data = data.replace( "</pre>", "");
                data = { "error":true, "mensaje_error":data };
            }
            if( typeof( function_pr ) == "function" )
            {
                function_pr( data );
            }
        }
    );
}
/***************************************************************************************************************/
/**
 * elimina de un array el indice indicado con la variable key
*/
var sliceByPos = function( array, key )
{
  var a_tmp = [];
  for(i=0; i<array.length; i++){
    if(i != key){
      a_tmp[a_tmp.length] = array[i];
    }
  }
  return a_tmp;
}

updateElmFromJSON = function( o_JSON )
{
    var numeroElementos = o_JSON.length;
    for ( var i = 0; i < numeroElementos; i++) 
    {
        if ( $( o_JSON[i][0] ) ) 
        {
            switch ( $( o_JSON[i][0] ).tagName ) 
            {
                case 'TD'      :
                    Element.update( o_JSON[i][0], o_JSON[i][1] );
                break;
                case 'INPUT'   :
                    $( o_JSON[i][0] ).value = o_JSON[i][1];
                break;
                case 'SELECT'  :
                    var objDDL = $( o_JSON[i][0] );
                    if ( typeof( cont ) == 'undefined' ) 
                    {
                        var cont = 0;
                        objDDL.options.length = 0;
                    }
                    var a_contentValues = o_JSON[i][1].split( "_;_" );
                    var value = a_contentValues[0];
                    var text = a_contentValues[1];
                    var option = new Option( text, value );
                    try 
                    {
                        objDDL.add( option, null );
                    } 
                    catch ( e ) 
                    {
                        objDDL.add( option, -1 );
                    }
                    cont++;
                break;
            }
        }
        else 
        {
            if ( o_JSON[i][0].indexOf( "function" ) > -1 ) 
            {
                eval( "scriptEval = " + o_JSON[i][0] );
                scriptEval();
            }
        }
    }
}

cargarOpcionesMI = function( j )
{
	$( ".opcionI" ).removeClass( 'textMenuOver' );
	$( ".opcionI" )
	.each
	( 
        function ( index, element ) 
        {
			if($(element).attr( "id")==j){
				$(element).addClass('textMenuOver');
			}else{
				$(element).addClass('textMenu');
			}
        }
    );
}

function padLeft( nr, n, str)
{
    return Array( n - String( nr ).length + 1 ).join( str || '0' ) + nr;
}

/**
 * Funcion que devuelve la fecha actual y la fecha modificada n dias
 * Tiene que recibir el numero de dias en positivo o negativo para sumar o
 * restar a la fecha actual.
 * Ejemplo:
 *  mostrarFecha(-10) => restara 10 dias a la fecha actual
 *  mostrarFecha(30) => añadira 30 dias a la fecha actual
 */
function mostrarFecha( fecha_desde, days )
{
    milisegundos = parseInt( 35 * 24 * 60 * 60 * 1000 );

    fecha = new Date( fecha_desde + "T10:00:00Z" );
    day = fecha.getDate();
    // el mes es devuelto entre 0 y 11
    month = fecha.getMonth() + 1;
    year = fecha.getFullYear();

    //document.write("Fecha actual: "+day+"/"+month+"/"+year);

    //Obtenemos los milisegundos desde media noche del 1/1/1970
    tiempo = fecha.getTime();
    //Calculamos los milisegundos sobre la fecha que hay que sumar o restar...
    milisegundos = parseInt( days * 24 * 60 * 60 * 1000 );
    //Modificamos la fecha actual
    total = fecha.setTime( tiempo + milisegundos );
    day   = fecha.getDate();
    month = fecha.getMonth() + 1;
    year  = fecha.getFullYear();

    //alert( "Fecha modificada: "+day+"/"+month+"/"+year );
    return year + "-" + padLeft( month, 2 ) + "-" + padLeft( day, 2 );
}

//VALIDACIONES EXTRAS
function NumCheckEntero( e, field )
{
    key = e.keyCode ? e.keyCode : e.which
    //console.log( key );
    //console.log( e.which );
    if ( e.which == 0 ){ return true; }
    if ( e.which == 8 ) return true;
    if ( key == 9 ) return true;
    if ( key == 46 ) return false;
    if ( key > 47 && key < 58 ) 
    {
        if ( field.value == "" ) return true
        regexp = /.[0-9]{10}$/
        return !( regexp.test( field.value ) )
    }
    return false
}
// onkeypress="return NumCheckEntero( event, this );"
function NumCheckDecimal( e, field )
{
    key = e.keyCode ? e.keyCode : e.which
    //console.log( key );
	if ( e.which == 0 ){ return true; }
    if ( e.which == 8 ) return true
    if ( key == 9 ) return true
    if ( key > 47 && key < 58 ) 
    {
        if ( field.value == "" ) return true
        regexp = /.[0-9]{10}$/
        return !( regexp.test( field.value ) )
    }
    
    if ( key == 46 ) 
    {
        if ( field.value == "" ) return false
        regexp = /^[0-9]+$/
        return regexp.test( field.value )
    }
    return false
}

function ImputCheckAlphanumeric( event ) 
{
    var regex = new RegExp( "^[a-zA-Z0-9\b]+$" );
    var key = String.fromCharCode( !event.charCode ? event.which : event.charCode );
    
    //exepciones
    if( event.keyCode == 9 )
    {
        return true;
    }

    if ( !regex.test( key ) )
    {
       event.preventDefault();
       return false;
    }
}
// onkeypress="return NumCheckDecimal( event, this );"

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//UTILITARIOS PARA ENVENTOS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
    Util para Cuando se va a guardar algo se muestre un cargador:
    <div id="s_ImagenLoad" style="display: none;"><img src="<?php echo Constantes::ROOT_DIR_APP ?>/web/images/progress.gif" border="0"/>&nbsp;<label class="laber req">Procesando...</label></div>
*/
mostrarCargaImg = function( id_elm ){ if ( typeof( id_elm ) == 'undefined' ){ id_elm = "s_ImagenLoad"; } $( '#' + id_elm ).show(); }
ocultarCargaImg = function( id_elm ){ if ( typeof( id_elm ) == 'undefined' ){ id_elm = "s_ImagenLoad"; } $( '#' + id_elm ).hide(); }

mostrarMensajeError = function( s_MensajeError )
{
    $( "#resultContent" ).html( '<div id="mensaje_error_content" class="error">' + s_MensajeError + '</div>' );
    setTimeout( function(){ $( "#mensaje_error_content" ).fadeOut( 800 ).fadeIn( 800 ).fadeOut( 500 ).fadeIn( 500 ).fadeOut( 300 ); }, 4000 );
}

blockContent = function( s_IdElement )
{
    $( '#' + s_IdElement ).block
            ( 
                { 
                    message: null,
                    css: { cursor: 'context-menu' }
                } 
            ); 
    $( ".blockUI" ).css( "cursor", "context-menu" );
    $( '.blockUI.blockOverlay' ).html( '<img src="/sisventa/web/images/common/indicator_big.gif" style="max-width: 70%; max-height: 70%; position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0; ">' );
};
unBlockContent = function( s_IdElement )
{
    $( '#' + s_IdElement ).unblock();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//UTIL PARA VALIDAR FECHAS NO MAYOR
function validate_fechaMayorQue( fechaInicial, fechaFinal )
{
    valuesStart = fechaInicial.split( "-" );
    valuesEnd   = fechaFinal.split( "-" );

    // Verificamos que la fecha no sea posterior a la actual
    var dateStart = new Date( valuesStart[0],(valuesStart[1]-1),valuesStart[2] );
    var dateEnd   = new Date( valuesEnd[0],(valuesEnd[1]-1),valuesEnd[2] );
    if( dateStart > dateEnd )
    {
        return true;
    }
    return false;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//FUNCIONES
//-----------> pregunta si se tiene un atributo especifico
$.fn.hasAttr = function( name ) 
{  
   return this.attr(name) !== undefined;
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///
///mas funciones
disabledButton = function( elm_id ){ $( "#" + elm_id ).prop( 'disabled', true ); }
enabledButton  = function( elm_id ){ $( "#" + elm_id ).prop( 'disabled', false ); }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//para pasar de input a label - especialmente para las views
convertirTextoTodosLosInputs = function()
{
    //$( "#form1 input, #form1 select" ).replaceWith
    $( "#form1 input:text, #form1 select, textarea" ).replaceWith
    (
        function () 
        {
            var nodeName = $( "#" + this.id ).prop( 'nodeName' );
            var nodeType = $( "#" + this.id ).prop( 'type' );
            
            if( this.id )
            {
                switch( nodeName )
                {
                    case "SELECT":
                        return '<label class=labelData >' + $( "#" + this.id + " option:selected" ).text() + '</label>';
                    break;
                    case "TEXTAREA":
                    case "INPUT":
                        switch( nodeType )
                        {
                            case "hidden":
                                pr( nodeType );
                                
                                return true;
                            break;
                            case "textarea":
                            case "text":
                                return '<label class=labelData >' + $( "#" + this.id ).val() + '</label>';
                            break;
                            case "button":
                                $( "#" + this.id ).remove();
                            break;
                            case "checkbox":
                                if( $( "#" + this.id ).is( ':checked' ) )
                                {
                                    return "<input type='checkbox' checked disabled />";
                                }
                                else
                                {
                                    return "<input type='checkbox' disabled />";
                                }
                            break;
                        }
                    break;
                }
                return '<label class=labelData >&nbsp;</label>';
            }
            else
            {                
                return '<label class=labelData >' + $( this ).val() + '</label>';
            }
        }
    );
}

convertirDisabledTodosLosInputs = function()
{
    //pr( "Ingresa" );

    $.each
    (
        $('input, select, textarea, button'), function()
        {
            //pr( this );
            var nodeName = typeof $( this ).attr( 'nodeName' ) === 'undefined' ? $( this ).prop( 'nodeName' ) : $( this ).attr( 'nodeName' );
            var nodeType = $( this ).attr( 'type' );

            //console.log( nodeName + " - " + nodeType );

            if( $( this ).length > 0 )
            {
                switch( nodeName )
                {
                    case "SELECT":
                        $( this ).prop( "disabled", true );
                        break;
                    case "TEXTAREA":
                        //pr( this );
                        $( this ).prop( "disabled", true );
                        break;
                    case "INPUT":
                        switch( nodeType )
                        {
                            case "textarea":
                                //pr( this );
                                break;
                            case "text":
                                //pr( this );
                                $( this ).prop( "disabled", true );
                                break;
                            case "button":
                                //$( this ).prop( "disabled", true );
                                break;
                            case "checkbox":
                                $( this ).prop( "disabled", true );
                                break;
                            case "hidden":
                                //$( this ).remove();
                                break;
                        }
                        break;
                    case "BUTTON":
                        //pr( $( this ).attr('class') );
                        //pr( $( this ).attr('class').indexOf( 'no-disabled' ) );
                        if( $( this ).attr('class').indexOf( 'no-disabled' ) <= 0 )
                        {
                            $( this ).prop( "disabled", true );
                        }
                        break;
                }
            }
        }
    );
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//mensaje de alerta - bootstrap 4
showAlertBootStrap = function( elm_id_content, class_default, message_alert )
{
    //Click event to scroll to top
    $( 'html, body' ).animate( { scrollTop : 0 }, 800 );
    $( "#" + elm_id_content ).show();
    var html_alert = '<div class="alert ' + class_default + ' alert-dismissible fade show" role="alert"> ' +
            '' + message_alert +
            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                '<span aria-hidden="true">&times;</span>' +
            '</button>' +
        '</div>';
    $( "#" + elm_id_content ).html( html_alert );
    setTimeout( function(){ $( "#" + elm_id_content ).fadeOut( 800 ).fadeIn( 800 ).fadeOut( 500 ).fadeIn( 500 ).fadeOut( 300 ); }, 10000 );
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

if ( !String.prototype.trim ) 
{
	(
        function() 
        {
        	// Make sure we trim BOM and NBSP
        	var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
        	String.prototype.trim = function() 
        	{
        		return this.replace( rtrim, '' );
        	};
        }
    )();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getCookie( c_name )
{
    //alert(document.cookie); //-----alerta de prueba-----
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1)
        {
            c_start=c_start + c_name.length+1
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return document.cookie.substring(c_start,c_end)
        }
    }
    return ""
}

function setCookie( c_name, value, expiredays, path, domain, secure )
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()-1);
    expiredays 	= ("; expires="+exdate.toGMTString()) ;
    document.cookie = c_name+ "=" +value+expiredays;

    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    expiredays 	= ((expiredays==null) ? "" : "; expires="+exdate.toGMTString()) ;
    path 		= ((path == null) ? "" : "; path=" + path) ;
    domain 		= ((domain == null) ? "" : "; domain=" + domain) ;
    secure 		= ((secure == null) ? "" : "; secure");

    document.cookie = c_name+ "=" +value+expiredays;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////