/**
 * *************** GLOBALES ***************
 */
var urlTop  = " " + window.location;
var SID = "SID=1";
if( urlTop.indexOf( "?" ) > 0 )
{
    SID = urlTop.split( "?" ).pop();
}
var urlProcesos     =   "procesos.php?" + SID;
var urlProductos    =   "productos.php?" + SID;
var urlFunciones    =   "funciones.php?" + SID;
var urlElementos    =   "elementos.php?" + SID;
var urlEquipos      =   "equipos_gestion.php?" + SID;
var urlUsers        =   "usuarios.php?" + SID;
var urlCart         =   "carrito.php?" + SID;

var recuHumaArr = [];
var switchIniFin = 'ini';
var componentes = [];
var rm_equipos_id = [];
initArrayValues( 'Component_' );
var currentZIndex = 1;
var activeCtrl = false;
/**
 *  Rango de ventanas y ventanas abiertas
 */
var rango = 20;
var ventanas = 0;
var ventanasEmergentes = [
    'newInvitaAlertDiv',
    'newCommentsAlertDiv',
    'recuHumaDiv',
    'acti_deta_div',
    'acti_comment_div',
    'acti_comment_deta_div',
    'detalle_mensaje',
    'captura_mensaje_alerta',
    'nuevaTareaDiv',
    'attachFiles',
    'chkHorariosDiv',
    'alertaNuevaTarea',
    'userParentDiv',
    'recuMateDiv',
    'recuMateParams'
];
var selectHour = {
    'stat':0,
    'h1':0,
    'h2':0
};
var selectHourE = {
    'stat':false,
    'col1':false,
    'row1':false,
    'col2':false,
    'row2':false,
    'date1':false,
    'date2':false,
    'hour1':false,
    'hour2':false
};
/**
 *  *************** FUNCIONES ***************
 */
/**
 * Coordenadas iniciales de ventanas emergentes
 */
function initPosition()
{
    var x = $( 'mainContainer' ).getPosition().x.toInt();
    var y = $( 'mainContainer' ).getPosition().y.toInt();
    var obj = { 'x' : x, 'y' : y };
    return obj
}
/**
 *  checar vigencia
 */
function getSelectionStart(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', o.value.length)
		if (r.text == '') return o.value.length
		return o.value.lastIndexOf(r.text)
	} else return o.selectionStart
}
/**
 *  checar vigencia
 */
function getSelectionEnd(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveStart('character', -o.value.length)
		return r.text.length
	} else return o.selectionEnd
}

/**
 *  cambia el foco a otro input
 */
function changeCell( evnt, el, maxCols, maxRows )
{
    code = ( window.ie ? evnt.keyCode : evnt.which );
    var pos = getSelectionStart( el );
    var id = el.id.split( '-' );
    var pre = id[0];
    var col = parseInt( id[ 1 ] );
    var row = parseInt( id[ 2 ] );

    if( code == 37 )
    {
        if( pos  == 0 )
        {
            if( col == 0 && row == 0 )
            {
                return false;
            }
            else
            {
                if( col == 0 )
                {
                    $( pre + '-' + maxCols + '-' + ( row - 1 ) ).focus();
                }
                else
                {
                    $( pre + '-' + ( col - 1 ) + '-' + row ).focus();
                }
            }
        }
    }
    else if ( code == 39 || code == 13 )
    {
        if( pos == el.value.length )
        {
            if( col == maxCols && row == maxRows )
            {
                return false;
            }
            else
            {
                if( col == maxCols )
                {
                    $( pre + '-0-' + ( row + 1 ) ).focus();
                }
                else
                {
                    $( pre + '-' + ( col + 1 ) + '-' + row ).focus();
                }
            }
        }
    }
    else if( code == 38 )
    {
        if( row > 0 )
        {
            $( pre + '-' + col + '-' + ( row - 1 ) ).focus();
        }
    }
    else if( code == 40 )
    {
        if( row < maxRows )
        {
            $( pre + '-' + col + '-' + ( row + 1 ) ).focus();
        }
    }
    else if( code == 36 )
    {
        if( activeCtrl )
        {
            $( pre + '-0-0' ).focus();
            activeCtrl = false;
        }
        else
        {
            $( pre + '-0-' + row).focus();
        }
    }
    else if( code == 35 )
    {
        if( activeCtrl )
        {
            $( pre + '-' + maxCols + '-' + maxRows ).focus();
            activeCtrl = false;
        }
        else
        {
            $( pre + '-' + maxCols + '-' + row ).focus();
        }
    }
    else if( code == 17 )
    {
        activeCtrl = true;
    }
    else
    {
        activeCtrl = false;
        //alert( code );
    }
}
/**
 *  hace un scroll al elemento
 */
function scrollTable( el )
{
    X = el.scrollLeft;
    Y = el.scrollTop;
    $( 'headerDiv' ).scrollTo( X, 0 );
    $( 'leftDiv' ).scrollTo(0, Y );
}
/**
 *  checar vigencia
 */
function combo( obj )
{
    var url =   urlElementos + "&elemento=combo";

    for( var o in obj )
    {
       url += "&" + o + "=" + obj[ o ];
    }
    var myAjax = new Ajax( url,
        {
            method  :   'get',
            update  :   $( obj.div ),
            onComplete : function()
            {
                //preLoader(0);
            }
        }
    ).request();
}
/**
 *  PRINT_R  como el de php pero para los arreglos esta haciendo algo raro por el momento
 *  solo esta funcionnando bien con los objetos
*/
function print_r( Obj )
{
    var string = "";
    var nivel = arguments[1] ? parseInt( arguments[1] ) : 0;
    var tabs = "";
    for( var i = 0; i < parseInt( nivel ); i++ )
    {
        tabs += "\t";
    }
    if( Obj.constructor == Array ||
        Obj.constructor == Object)
    {
        string += typeof( Obj ) + "\n" + tabs +"(\n";
        for( var p in Obj)
        {
            if( Obj[p].constructor == Array ||
                Obj[p].constructor == Object )
            {
                string +=   tabs + "\t[" + p + "] => " +
                            print_r( Obj[ p ], ( nivel + 1 ) ) ;
            } else {
                string += tabs + "\t[" + p + "] => " + Obj[ p ] + "\n";
            }
        }
        string += tabs + ")\n";
    }
    return string;
      
}
/**
 *  envia el foco al siguiente input
 */
function nextInput( ev, id )
{
    code = ( window.ie ? ev.keyCode : ev.which );

    if( code == 13 )
    {
        $( id ).focus();
        return true;
    }
}
/**
 *  Muestra u oculta el preloader
 */
function preLoader( showHide )
{
    var cId = "tdContainer";
    var pId = "preloader";

    if( showHide == 'show' || showHide == 1 )
    {
        var display = 'inline';
        if( arguments[1] )
        {
            cId = arguments[1]
        }
        $( pId ).style.top      = $( cId ).getPosition().y ;
        $( pId ).style.left     = $( cId ).getPosition().x ;
        $( "preloaderTable" ).style.width    = $( cId ).getStyle('width').toInt();//$( cId ).style.width;
        $( "preloaderTable" ).style.height   = $( cId ).getStyle('height').toInt();//$( cId ).style.height;
        $( pId ).style.display = display;
        showOver( pId );
    }
    else
    {
        var display = 'none';
       // $( pId ).style.display = display;
        return fadeOut( $( pId ) );
    }
    
}
/**
 *  desaparece gradualment un eleento
 */
function fadeOut( box )
{
    var duracion = ( arguments[1] ? arguments[1] : 700 );
    var fx = box.effects({duration: duracion, transition: Fx.Transitions.Quart.easeOut});
    /* AJAX Request here... */
    
    fx.start(
        {
        }).chain(function()
            {
                this.start.delay(100, this,
                    {'opacity' : 0
                    });
            }).chain(function()
            {
                box.style.display="none";
                this.start.delay(50, this, {'opacity' : 1});
            });
    return true;
            // $( 'loader' ).style.display = 'none';
}
/**
 *  checar vigencia
 */
function cargaTab( idTab, idContainer, idContent )
{
    preLoader(1, ( $('tabContainer') ? 'tabContainer' : idContainer ));
    var url =   urlFunciones + "&action=getTabs" + 
                "&idTab=" + idTab +
                "&idContent=" + idContent +
                "&idContainer=" + idContainer;
    var myAjax = new Ajax( url,
        {
            method  :   'get',
            update  :   $( idContainer ),
            onComplete : function()
            {
                preLoader(0);
            }
        }
    ).request();

}
/**
 *  carga la imagen de la seccion cargada
 */
function imgSection( seccion )
{
    var url = urlProcesos + "&action=imgSection&seccion=" + seccion;
    var request = new Json.Remote(url, 
        {
            onComplete : function( obj )
            {
                if( obj.complete == 'ok' )
                {
                    $( 'seccionTitulo' ).innerHTML = obj.pathImg;
                    correctPNG();
                }
            }
        }
    ).send();
}
/**
 *  carga la interface seleccionada del menu
 */
function goTo( action )
{
    closeAllWindows();
    if( action == 'monitor' )
    {
        userMonitor();
        return;
    }
    if( action == 'logout' )
    {
        logout();
    }
    else
    {
        if( action == 'equipos_pannel' )
        {
            //include( 'js/equipos.gestion.js',{'cache':false,'dom':true,'charset':'iso-8859-1'});
        }
        if( action == 'users_pannel' )
        {   
            include( 'js/user.gestion.js',{'cache':false,'dom':true,'charset':'iso-8859-1'} );
        }
        if( action == 'conceptos_setup' )
        {
            include( 'js/conceptos.gestion.js',{'cache':false,'dom':true,'charset':'iso-8859-1'} );
        }
        if( action == 'clients_pannel' )
        {
            include( 'js/client.gestion.js',{'cache':false,'dom':true,'charset':'iso-8859-1'} );
        }

        preLoader(1 ,( arguments[1] ? arguments[1] : 'mainContainer' ) );
        imgSection( action );
        var url = urlProcesos + "&action=" + action;
        var myAjax = new Ajax( url,
            {
                method  :   'get',
                update  :   $(( arguments[1] ? arguments[1] : 'mainContainer' )),
                onComplete  :   function()
                {
                    preLoader(0);
                    if( action == 'interface_setup' )
                    {
                        goTo( 'menu_interface_setup', 'mainMenu' );
                    }
                    if( action == 'index' )
                    {
                        goTo( 'index_menu', 'mainMenu' );
                    }
                    if( action == 'menu_interface_setup' )
                    {
                        makeDraggableComponents();
                    }
                    if( action == 'clients_pannel' )
                    {
                        setTimeout( "startSlider( 50,'area')" , 1000 );
                        setTimeout( "startSliderTabla({'id':'area2','idTabla':'segDiv','idContent':'sliderContent'} )" , 1000 );
                        setTimeout( "startSliderTabla({'id':'area3','idTabla':'segDiv','idContent':'sliderContent','mode':'vertical'} )" , 1000 );
                        setTimeout( "clienteAccordion()" , 1000 );
                    }
                    if( action == 'act_hoy' && arguments[2] )
                    {
                        obj = arguments[2];
                        show_activities( obj.date, obj.act_id );
                    }
                }
            }
        ).request();
    }
}
/**
 *  Inicializa el slider de la tabla de segmentos de cliente
 */
function startSliderTabla( obj ) // startIn, id, idTabla, idContent )
{
    if( $( obj.idContent ) )
    {
    var mySlide = new Slider(
        $( obj.id ),
        $( obj.id + 'knob'),
        {
            steps:  (   obj.mode == 'vertical'
                    ?   $( obj.idContent ).getStyle('height').toInt() - $( obj.idTabla ).getStyle('height').toInt()  
                    :   $( obj.idContent ).getStyle('width').toInt() - $( obj.idTabla ).getStyle('width').toInt()
                    ),
            mode : ( obj.mode ? obj.mode : 'horizontal' ),
            onChange: function( step )
            {
                if( obj.mode == 'vertical' )
                {
                    $( obj.idTabla ).scrollTo( $( obj.idTabla).scrollLeft, step);
                }
                else
                {
                    $( obj.idTabla ).scrollTo(step,$( obj.idTabla ).scrollTop);
                }
            }
        }
    ).set( ( obj.startIn ? obj.startIn : 0 ) );
    }
}
/**
 *  checar vigencia
 */
function getCombo( id, obj_table, obj_value, obj_text, obj_selected, obj_where )
{
    var url =   urlFunciones + "&action=getCombo" + 
                "&id_container=" + id +
                "&obj_table=" + obj_table +
                "&obj_value=" + obj_value +
                "&obj_text=" + obj_text +
                "&obj_selected=" + obj_selected + 
                "&obj_where=" + obj_where;

    $( id ).length = 0;
    add_option( id, 'Seleccione una opcion', '' );
    var request = new Json.Remote(
        url,
        {
            onComplete : function( obj )
            {
                if( obj.complete == 'ok' )
                {
                    for( var i = 0; i < obj.rs.length; i++ )
                    {
                       add_option( obj.id_container, obj.rs[i].optionText, obj.rs[i].optionValue );
                    }
                }
            }
        }
    ).send();
}
/**
 * checar vigencia
 *  agrega option a un select
 */
function add_option(id,txt,val)
{
    var newOption = new Element('option',{});
    if( window.ie )
    {
        newOption.innerText = txt;
    }
    else
    {
        newOption.text = txt;
    }
    newOption.value = val;
    newOption.selected = arguments[3];
    newOption.inject( id );
}
/**
 *  checar vigencia
 *  mueve un  elemento al centro de la pantalla
 */
function moveToCenter( id, obj )
{
    var limitTop    =   ( obj.limitTop  ? obj.limitTop  : 0 );
    var limitLeft   =   ( obj.limitLeft ? obj.limitLeft : 0 );
    var winW =  (   window.ie 
                ?   (   document.documentElement.offsetWidth
                    ?   document.documentElement.offsetWidth
                    :   document.body.offsetWidth
                    )
                :   window.innerWidth
                );
    var winH =  (   window.ie
                ?   (   document.documentElement.offsetHeight
                    ?   document.documentElement.offsetHeight 
                    :   document.body.offsetHeight
                    )
                :   window.innerHeight
                );

    var sizeW   =   $( id ).getStyle('width').toInt() / 2 ;//( $( id ).style.width  ? ( parseFloat( $( id ).style.width.replace('px','') ) / 2 ) : 1 );
    var sizeH   =   ( $( id ).style.height ? ( parseFloat( $( id ).style.height.replace('px','')) / 2 ) : 1 );
    var elLeft  =   ( ( winW / 2 ) - sizeW );
    var elTop   =   ( ( winH / 2 ) - sizeH );

    elTop   =   ( elTop < limitTop ? limitTop : elTop );
    elLeft  =   ( elLeft < limitLeft ? limitLeft : elLeft );

    $( id ).setStyles(
        {
         position   :   'absolute',
         left       :   elLeft  + 'px',
         top        :   elTop   + 'px'   
        }
       );
    
}
/**
 *  cambia el z-index de un elemento para que se vea encima de los demas
 */
function showOver(id )
{
    if( $( id ) )
    {
        currentZIndex++;
        $( id ).style.zIndex = currentZIndex;
    }
}
/**
 *  checar vigencia
 */
function changePosition( obj )
{
    var TopPos  =   $( obj ).getPosition().y;
    var LeftPos =   $( obj ).getPosition().x;
}
/**
 *  checar vigencia
 */
function draggableElement( id )
{
    showOver(id);
    $( id ).makeDraggable(
        {
            'container' : $('mainContainer'),
            onComplete : function()
            {
                
                changePosition(id);
                updateInterface();
            },
            onDrag : function()
            {
                var pos = {
                    "x": this.element.getStyle('left').toInt() + 1, 
                    "y": this.element.getStyle('top').toInt() + 1
                };
                $( 'divId' ).value = this.element.id;
                $( 'coordX' ).value = pos.x;
                $( 'coordY' ).value = pos.y;
            }
        }
    );
}
/**
 *  checar vigencia
 */
function ajustaInterface()
{
    var winW =  (   window.ie 
                ?   (   document.documentElement.offsetWidth
                    ?   document.documentElement.offsetWidth
                    :   ( document.body.offsetWidth - 25 )
                    )
                :   ( window.innerWidth - 25 )
                );
    var winH =  (   window.ie
                ?   (   document.documentElement.offsetHeight
                    ?   document.documentElement.offsetHeight 
                    :   document.body.offsetHeight
                    )
                :   ( window.innerHeight - 10 )
                );
    var newWidth = winW- $( 'mainMenu' ).getStyle('width').toInt();
    var newHeight= winH;
    $( 'principalTable' ).setStyle( 'height' , newHeight + 'px' );
}
/**
 *  checar vigencia
 */
function initArrayValues( prefix )
{
/*
    var url =   urlProcesos + "&action=initArray&prefix=" + prefix +
                "&user_components=1";
    var request = new Json.Remote( url,
        {
            onComplete : function( obj )
            {
                if( obj.complete == 'ok' )
                {
                    componentes = obj.componentes;
                }
                else
                {
                   // alert( obj.complete );
                }
            }
        }
    ).send();
    */
}
/**
 *  verifica que exista un elemento en un arreglo (arreglos simples)
 */
function inArray( el, arr )
{
    var rs = false;
    for( var i = 0; i < arr.length; i++ )
    {
        rs = ( el == arr[ i ] ? true : rs );
    }
    return rs;
}
function arrayDel( el, arr )
{
    var tmp = [];
    for( var i = 0; i < arr.length; i++ )
    {
        if( el != arr[ i ] )
        {
            tmp.push( arr[ i ] );
        }
    }
    return tmp;
}
/**
 *  checar vigencia
 */
function getComponent( comp, divId )
{
    var url =   urlProcesos + "&action=getComponent&editable=1&componentName=" + comp +
                "&interface_id=1" +
                "&divContainer=" + divId ;
    var myAjax  =   new Ajax( url,
        {
            method  :   'get',
            update  :   $( divId ),
            onComplete : function()
            {
                $( divId ).setStyles(
                    { 
                        'border' : 'none',
                        'cursor' : 'move'
                    }
                );
                $( divId ).addEvent( 'mousedown', function(){ draggableElement(this.id) });
            }
        }
    ).request();
}
/**
 *  checar vigencia
 */
function makeDraggableComponents()
{
    var drop = $('mainContainer');
    var dropFx = drop.effect('background-color', {wait: false}); 
    
    $$('.menuImgComponent').each( 
        function( item )
        {  
            item.addEvent('mousedown',
            function(e) 
            {
                e = new Event(e).stop();    
                var clone = this.clone()
                .setStyles(this.getCoordinates()) // this returns an object with left/top/bottom/right, so its perfect
                .setStyles({'opacity': 0.7, 'position': 'absolute'})
                .addEvent('emptydrop',
                function()
                {
                    this.remove();
                    drop.removeEvents();
                }
                ).inject( document.body );    
                
                drop.addEvents(
                    {
                        'drop': function() 
                        {
                            drop.removeEvents();
                            clone.remove();
                            //dropFx.start('7389AE').chain(dropFx.start.pass('ffffff', dropFx));
                            var tmpId = item.id.split( '_' );
                            tmpId.reverse();
                            tmpId.pop();
                            tmpId.reverse();
                            var newId = tmpId.join('_');
                            if( !inArray( newId, componentes ) )
                            {
                                //alert( newId );

                                componentes.push( newId );
                                //$( 'debug' ).innerHTML += newId + ' ' ;
                                $( 'preloaderTable' ).setStyles({'width':'50px','height':'50px'});
                                var newClone = $( 'preloader' ).clone();
                                newClone.setStyles(
                                    {   
                                        'position'  :   'static',
                                        'float'     :   'left',
                                        'display'   :   'inline',
                                        'border'    :   'solid 1px #cdcdcd'
                                    }
                                );
                                newClone.id = newId; 
                                newClone.inject(drop);
                                getComponent( newId, newClone.id );
                            }
                            else
                            {
                                alert( 'El componente ya esta en el escritorio' );
                            }
                        },
                        'over': function() 
                        {
                            //dropFx.start('98B5C1');
                        },
                        'leave': function() 
                        {
                            //dropFx.start('ffffff');
                        }
                    }
                );    
                var drag = clone.makeDraggable(
                    {
                        droppables: [drop]
                    }
                ); // this returns the dragged element
    
                drag.start(e); // start the event manual
            }
            );
    
        }
    );
}
/**
 *  arregla el canal alpha de los archivos PNG para internet explorer
 */
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
    var arVersion = navigator.appVersion.split("MSIE")
    var version = parseFloat(arVersion[1])
    if( window.ie && (version >= 5.5) && (document.body.filters)) 
    {
        //alert( "Explorer : " + version );
        for(var i=0; i<document.images.length; i++)
        {
            var img = document.images[i]
            var imgName = img.src.toUpperCase()
            if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
            {
                var imgID = (img.id) ? "id='" + img.id + "' " : ""
                var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                var imgStyle = "display:inline-block;" + img.style.cssText 
                if (img.align == "left") imgStyle = "float:left;" + imgStyle
                if (img.align == "right") imgStyle = "float:right;" + imgStyle
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                var strNewHTML = "<span " + imgID + imgClass + imgTitle
                + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
                img.outerHTML = strNewHTML
                i = i-1
            }
        }
    }    
}
/**
 *  FORMATOS
 */
/**
 * Campo numerico 
 * Solo permite la captura de numeros
 */
function numerico( evnt, id )
{
    var code = ( window.ie ? evnt.keyCode : evnt.which );
    if( 
        (   code >= 48 && code <= 57 ) ||
        (   code >= 96 && code <= 105 ) ||
        (   code >= 37 && code <= 40 ) ||
            code == 46 || code == 17 || code == 27 ||
            code == 8 || code == 0 || code == 13 || code == 9 ||
            code == 110 || code == 190
    )
    {
        return true;
    }
    return false;
}
/**
 *  verifica el formato de la hora capturada
 */
function formatoHora( id )
{
    var error = false;
    if( $( id ).value.indexOf( ':' ) > 0)
    {
        var dat = $( id ).value.split( ':' );
        var hora = dat[0].toInt();
        var minutos = dat[1].toInt();
        if( isNaN( hora ) || isNaN( minutos ) )
        {
            alert( "La hora y los minutos deben ser numeros" );
            error = true;
        }
        if( hora > 24 || hora < 0 )
        {   
            alert( "La hora debe ser de 0 a 24 " );
            error = true;
        }
        if( minutos < 0 || minutos > 59 )
        {
            alert( "Los minutos deben ser de 0 a 59 " );
            error = true;
        }
    }
    else
    {
        alert( "Formato incorrecto\nUtilice 'HH:MM' " );
        error = true;
    }

    if( error == true )
    {
        $( id ).value = '';
    }
}
/**
 *  rellena el input con la hora segun la mascara
 */
function completaHora( el )
{
    if( el.value.indexOf( ":" ) == 0 )
    {
        el.value = "00" + el.value;
    }
    if( el.value.length == 1 )
    {
        el.value = "0" + el.value + ":00";
    }
    if( el.value.length == 3 )
    {
        el.value += "00";
    }
    if( el.value.length == 4 )
    {
        el.value += "0";
    }
    if( el.value.indexOf( ":" ) > 0 )
    {
        var tmp = el.value.split( ":" );
        var v1 = tmp[0];
        var v2 = tmp[1];
        if( tmp[0].length == 1 )
        {
            v1 = "0" + parseInt( tmp[0] );
        }
        if( tmp[1].length == 1 )
        {
            v2 = "0" + parseInt( tmp[1] );
        }
        el.value = v1 + ":" + v2;
    }
    if( el.value.indexOf(":") < 0 )
    {
        var tmp = el.value;
        el.value = tmp.substr(0,2) + ":" + tmp.substr(2,4);
    }
    if( el.value.length > 5 )
    {
        el.value = el.value.substr(0,5);
    }
}
/**
 *  crea marcara de captura con formato HH:MM
 */
function mascaraHora( el, evnt )
{
    var code = ( window.ie ? evnt.keyCode : evnt.which );
    if( 
        ( code >= 48 && code <= 57 ) ||
        ( code >= 96 && code <= 105 ) ||
        code == 8 || code == 0 || code == 13
    )
    {
        if( el.value.length == 1 )
        {
            if( parseInt( el.value ) > 2 )
            {
                el.value = "0" + el.value;
            }
        }
        if( el.value.length == 2 )
        {
            if( parseInt( el.value ) > 23 )
            {
                 el.value = "0" + el.value.substr(0,1) + ":" + el.value.substr(1,1);
            }
            else  if( code != 8 )
            {
                el.value += ":";
            }
        }
        if( el.value.length == 4 )
        {
            var tmp = el.value.split(":");
            if( parseInt( tmp[1] ) > 5 )
            {
                el.value = tmp[0] + ":0" + tmp[1].substr(0,1);   
            }
        }
        return true;
    }
    else
    {
        if( code == 9 )
        {
            return true;
        }
        return false;
    }
}
/**
 *  checar vigencia
 */
function switchColor( id, col1, col2 )
{
    var currColor = $( id ).getStyle( 'background-color' );
    var color = ( currColor == "#" + col1 ? "#" + col2 : "#" + col1 );
    $( id ).setStyle('background-color' , color );
}
/**
 *  Cambia la vista de un elemento
 */
function switchDisplay( id )
{
    var displ = $( id ).getStyle('display' );
    $( id ).setStyle('display', ( displ == 'inline' ? 'none' : 'inline' ) );
}
/*  Actividades y tareas */
/**
 *  checar vigencia
 */
function detaHist( id )
{
    var url = urlProcesos + '&action=detaHist&id=' + id;
    var aja = new Ajax( url,
        {
            'method' : 'get',
            'update' : $( 'emptyDiv' ),
            'onComplete' : function()
            {
                $( 'emptyDiv' ).setStyles(
                    {
                        'position'  :   'absolute',
                        'top'       :   '150',
                        'left'      :   '150'
                    }
                );
                showOver( 'emptyDiv' );
            }
        }
    ).request();
}
/**
 * checar vigencia
 */
function ajustaTareas()
{
    for( var i = 0 ; i < 24; i++ )
    {
    }
}
/**
 *  cambia la imagen
 */
function switchImage( el )
{
    var url = $( el ).innerHTML;
    if( url.indexOf( 'Mas' ) > 1 )
    {
        var sr = url.replace( 'Mas','Menos' );
    }
    else
    {
        var sr = url.replace('Menos','Mas');
    }
    $( el ).innerHTML = sr;
}
/**
 *  carga el formulario de captura de las tareas
 */
function nuevaTarea()
{
    var obj = arguments[1] ? arguments[1] : {'horainicial':false,'horafinal':false};
    rm_equipos_id = [];
    recuHumaArr = [];
    if( $( 'nuevaTareaDiv' ) ) $( 'nuevaTareaDiv' ).remove();
    var pos = getAvailablePosition();
    var newDiv = new Element( 'div', { 'id':'nuevaTareaDiv' }).inject( document.body );
    $( 'nuevaTareaDiv' ).setStyles(
        {   'position'      :   'absolute',
            'top'           :   pos.y + 'px',
            'left'          :   pos.x + 'px'
        }
    );
    var aja = new Ajax( urlProcesos,
        {   'method'    :   'get',
            'data'      :   {   'action'    :   'nuevaTareaForm',
                                'date'      :   $( 'acti_fech_hidden' ).value,
                                'parent'    :   ( arguments[0] ? arguments[0] : 0 )
                            },
            'update'    :   $( 'nuevaTareaDiv' ),
            'onComplete' : function()
            {
                showOver('nuevaTareaDiv');
                $( 'acti_tipo' ).focus();
                if( obj.horainicial )
                {
                    $( 'acti_hora_ini' ).value = obj.horainicial;
                }
                if( obj.horafinal )
                {
                    $( 'acti_hora_fin' ).value = obj.horafinal;
                }
            }
        }
    ).request();
}
/**
 * Valida el tipo de ubicacion
 */
function validaTipoUbicacion( valor )
{
    var displ = 'none';
    if( valor > 1 )
    {   
        displ = 'inline';
    }
    $( 'acti_ubicacion' ).setStyle('display',displ);
}
/**
 * Edicion de tareas
 */
function editaTarea( acti_id )
{
    rm_equipos_id = [];
    recuHumaArr = [];
    if( $( 'nuevaTareaDiv' ) ) $( 'nuevaTareaDiv' ).remove();
    var pos = getAvailablePosition();
    var newDiv = new Element( 'div', { 'id':'nuevaTareaDiv' }).inject( document.body );
    $( 'nuevaTareaDiv' ).setStyles(
        {   'position'      :   'absolute',
            'top'           :   pos.y + 'px',
            'left'          :   pos.x + 'px'
        }
    );
    var aja = new Ajax( urlProcesos,
        {   'method'    :   'get',
            'data'      :   {   'action'    :   'editarTareaForm',
                                'acti_id'      :   acti_id
                            },
            'update'    :   $( 'nuevaTareaDiv' ),
            'onComplete' : function()
            {
                showOver('nuevaTareaDiv');
                $( 'acti_tipo' ).focus();
                chkRecuHuma( acti_id );
                chkRecuMate( acti_id );
            }
        }
    ).request();
        
}
/**
 *  Eliminacion de tareas
 */
function eliminaTarea( acti_id )
{
    $( 'deleteActi' ).disabled = 'disabled';
    if( confirm( 'Desea eliminar la actividad? ' ) == true )
    {
        var jsn = new Json.Remote(
            urlProcesos + '&action=delete_acti&acti_id=' + acti_id,
            {
                'onComplete' : function( obj )
                {
                    if( obj.complete == 'ok' )
                    {
                        $( 'acti_deta_div' ).remove();
                        var d = new Date();
                        var Y = d.getFullYear();
                        var M = d.getMonth() + 1;
                        var D = d.getDate();
                        showCalendar( ( M < 10 ? '0' + M : M ), Y, D );
                        actualizaTareasAtrazadas();
                        show_activities(obj.fech);
                        //confirmAttachFiles(obj.acti_id);
                    }
                }
            }
        ).send();
    }
    else
    {
        $( 'deleteActi' ).disabled = false;
    }
}
/**
 *  Cancela la finalizacion de la tarea
 */
function cancelaTareaFin()
{
    var el = $$( 'input.statTarea' );
    for( var  i = 0; i < el.length; i++ )
    {
        el[i].checked = false;
    }
    $( 'alertaNuevaTarea' ).setStyle('display','none');
    $('finalizarBtn').setStyle('display','none');
    $( 'tareaId' ).value = '';
    $( 'tareaDivId' ).value = '';
    $( 'acti_fin_desc' ).value = '';
}
/**
 * checar vigencia
 */
function validaTareaStatus()
{
    var el = $$( 'input.statTarea' );
    var fin_desc = escape( $( 'acti_fin_desc' ).value );
    var op = false;
    for( i = 0; i < el.length; i++)
    {
        op = ( el[i].checked == true ? el[i].value : op );
    }
    if( op == false )
    {
        alert( 'Seleccione una de las opciones o de click en cancelar' );
        return;
    }
    if( op == 1 )
    {
        nuevaTarea( $('tareaId').value );
    }
    if( window.ie )
    {
        window.parent.tareasIframe.saveStatus($('tareaId' ).value,$('tareaDivId').value,fin_desc);
    }
    else
    {
        parent.tareasIframe.saveStatus($('tareaId').value,$('tareaDivId').value,fin_desc);
    }
    cancelaTareaFin();
}
/**
 *  actualiza vista de tareas pendientes
 */
function actualizaTareasAtrazadas()
{
    
    if( $( 'componente_content_4' ) )
    {
        var tipo = $( 'tareasAMP' ) ? $( 'tareasAMP' ).value : 0;
        var url = urlProcesos + "&action=getTareasAtrazadas&tipo=" + tipo;
        var aja =   new Ajax( url,
            {
                'method' : 'get',
                'update' : $( 'componente_content_4' ),
                'onComplete' : function()
                {
                    var d = new Date();
                    var Y = d.getFullYear();
                    var M = d.getMonth() + 1;
                    var D = d.getDate();
                    showCalendar( ( M < 10 ? '0' + M : M ), Y, D );
                }
            }
        ).request();
    }
}
/**
 *  checar vigencia
 */
function getHistory(id)
{
    var url = urlProcesos + "&action=getTareasHistorial&id=" + id;
    var aja = new Ajax( url,
        {
            'method' : 'get',
            'update' : $( 'history' )
        }
    ).request();
}
/**
 *  carga formulario de contactos
 */
function cargaContForm( clie_id )
{
    var url = urlProcesos + "&action=cargaContForm&clie_id=" + clie_id;
    var ajs = new Ajax( url,
        {
            'method' : 'get',
            'update' : $( 'contDivForm' )
        }
    ).request();
}
/**
 *  checar vigencia
 */
function switchTareasAMP( tipo )
{
    $( 'tareasAMP' ).value = 0; //tipo;
    /*
    $( 'title_component_4' ).innerHTML =    (   tipo == 0
                                            ?   'Tareas atrazadas'
                                            :   (   tipo == 1
                                                ?   'Tareas de ma&ntilde;a'
                                                :   'Tareas de pasado ma&ntilde;a'
                                                )
                                            );
                                            */
    actualizaTareasAtrazadas();
}
/**
 * Guardando la actividad
 */
function saveActividad()
{
    if( $( 'recuHumaDiv' ) ) $( 'recuHumaDiv' ).remove();
    if( $( 'recuMateDiv' ) ) $( 'recuMateDiv' ).remove();
    var el = $$( 'input.acti', 'textarea.acti', 'select.acti' );
    var url = urlProcesos + "&action=saveActivities&alerta=" + $( 'alerta' ).value;
    for(  var i = 0; i < el.length; i++ )
    {
        if( el[i].value != '' )
        {
            url += "&" + el[i].id + '=' + escape( el[i].value );
        }
    }
    if( $( 'acti_tipo' ).value == '' )
    {
        alert( 'seleccione un tipo de actividad' );
        $( 'acti_tipo' ).focus();
        return;
    }
    if( $( 'acti_objetivo' ).value == '' )
    {
        alert( 'Se requiere de un objetivo' );
        $( 'acti_objetivo' ).focus();
        return;
    }

    $( 'saveActiBtn' ).disabled='disbled';
    if( arguments[0] != '' && arguments[0] != undefined )
    {
        url += "&acti_id=" + arguments[0];
    }
    if( recuHumaArr.length > 0 )
    {
        url += "&recuHuma=" + recuHumaArr;
    }
    if( $( 'rm' ).value != '' )
    {
        url += "&r_m=" + $( 'rm' ).value;
    }
    var jsn = new Json.Remote( url,
        {
            onComplete : function( obj )
            {
                if( obj.complete == 'ok' )
                {
                    var d = new Date();
                    var Y = d.getFullYear();
                    var M = d.getMonth() + 1;
                    var D = d.getDate();
                    showCalendar( ( M < 10 ? '0' + M : M ), Y, D );
                    actualizaTareasAtrazadas();
                    show_activities(obj.fech);
                    confirmAttachFiles(obj.acti_id);
                }
                else
                {
                    alert(obj.complete);
                }
            }
        }
    ).send();
}
/**
 *  checar vigencia
 */
function reload_acti()
{
    show_activities( $('acti_fech_hidden').value );
}
/**
 *  Descarga el archivo seleccionado
 */
function downloadFile( path )
{
    if( $( 'downLoadFiles' ) )
    {
        $( 'downLoadFiles' ).remove();
    }
    var iFrame = new Element( 'iframe',{'id':'downLoadFiles'} ).inject( document.body );
    $( 'downLoadFiles' ).setStyles(
        {   'width' : '1px',
            'height' : '1px',
            'position' : 'absolute',
            'top' : '0px',
            'left' : '0px'
        }
    );
    $( 'downLoadFiles' ).src = 'downloadFiles.php?path=' + path + ( arguments[1] ? '&name=' + arguments[1] : '' );
}
/**
 *  elimina archivo de la lista de archivos adjuntos en la tarea
 */
function deleteFile( obj )
{
    var jsn = new Json.Remote(
        urlProcesos + '&action=delete_file&tableName=' + obj.tableName +
        '&columnId=' + obj.columnId +
        '&id=' + obj.id +
        '&archivo_id=' + obj.archivo_id,
        {
            'onComplete' : function( jobj )
            {
                if( jobj.complete == 'ok' )
                {
                    updateFileList( obj.id );
                }
            }
        }
    ).send();
}
/**
 *  carga la lista de archivos adjuntos en la tarea
 */
function updateFileList(acti_id)
{
    var aja = new Ajax( urlProcesos,
        {   'method' : 'get',
            'data' : {'action':'update_file_list','acti_id':acti_id},
            'update' : $('fileList'),
            'onComplete' : function()
            {
                preLoader(0);
            }
        }
    ).request();
}
/**
 *  checar vigencia
 */
function setUploadFile( el )
{
    $( 'fileName' ).value = el.value;
}
/**
 *  Ventana de confirmacion para agregar archivos a la tarea
 */
function confirmAttachFiles( acti_id )
{
    if( $( 'attachFiles' ) ) $( 'attachFiles' ).remove();
    var pos = getAvailablePosition();
    var DIV = new Element( "div", { "id" : "attachFiles"} ).inject( document.body );
    $( 'attachFiles' ).setStyles(
        {   'position'  :   'absolute',
            'top'       :   pos.y + 'px',
            'left'      :   pos.x + 'px'
        }
    );
    var aja = new Ajax( urlProcesos,
        {   'method'    :   'get',
            'data'      :   {   'action' : 'attachFiles',
                                'acti_id'   :   acti_id
                            },
            'update'    :   $( 'attachFiles' ),
            'onComplete' : function()
            {
               $( 'nuevaTareaDiv' ).remove(); 
            }
        }
    ).request();
    showOver( 'attachFiles' );
}
/**
 * Finalizador de tareas
 */
function endActi( idTarea, idDiv )
{
    if( $( 'alertaNuevaTarea' ) ) $( 'alertaNuevaTarea' ).remove();
    var pos = getAvailablePosition();
    var DIV = new Element( 'div', { 'id': 'alertaNuevaTarea' }).inject( document.body );
    $( 'alertaNuevaTarea' ).setStyles(
        {   'position'  :   'absolute',
            'top'       :   pos.y + 'px',
            'left'      :   pos.x + 'px'
        }
    );
    var ax = new Ajax( urlProcesos,
        {   'method'    :   'get',
            'data'      :   {'action':'endActi'},
            'update'    :   $( 'alertaNuevaTarea' ),
            'onComplete'    :   function()
            {
                $( 'tareaId' ).value = idTarea;
                $( 'tareaDivId' ).value = idDiv;
            }
        }
    ).request();
}
/**
 *  Comentario de cierre de tarea forzoso!!
 */
function valida_finalizar_comentario()
{
    if( $( 'acti_fin_desc' ).value != '' && $( 'acti_fin_desc' ).value.length > 3 )
    {
        $('finalizarBtn').setStyle('display','inline');
    }
    else
    {
        $('finalizarBtn').setStyle('display','none');
    }
}
/**
 *  checar vigencia
 */
function allDay( el )
{
    if( el.checked == true )
    {
        display = 'none';
    }
    else
    {
        display = 'inline';
    }
        $( 'acti_hora_ini' ).setStyle('display',display);
        $( 'acti_hora_fin' ).setStyle('display',display);
}
/**
 *  checar vigencia
 */
function showClock( el )
{
    var id = 'tmpDiv';
    var div = new Element( 'div', {
        'id' : id
    });
    div.inject( $( 'emptyDiv' ),'after' );
    $( id ).setStyles(
        {
            'position'  :   'absolute',
            'width'     :   '100px',
            'height'    :   '150px',
            'overflow'  :   'auto',
            'background' : '#ffffff',
            'border-style'  :   'solid',
            'border-width'  :   '1px',
            'border-color'  :   '#cdcdcd',
            'top'   :   ( $(el.id).getPosition().y + 20 ) + 'px',
            'left'  :   $(el.id).getPosition().x + 'px'
        }
    );
    
    var cad = '';
    var h1 = $( 'acti_hora_ini' ).value.split( ':' );
    var curr_hour = h1[0] + '' + parseInt( h1[1] );
    var H = ( el.id == 'acti_hora_fin' ? curr_hour : 0 );

    for( var i = H; i < 24; i++ )
    {
        var hora =  (   i == 0
                    ?   12
                    :   (   i > 12
                        ?   i  - 12
                        :   i
                        )
                    );
        hora = ( hora < 10 ? '0' + hora : hora );
        var meridiano = ( i < 12 ? 'am' : 'pm' );
        for( var min = 0; min < 60; min += 30 )
        {
            var tmpH = parseFloat( i + '.' + min );
            if( el.id == 'acti_hora_fin' && tmpH < curr_hour )
            {
            }
            else
            {
                var txtMin = ( min < 10 ? '0' + min : min )
                cad +=  "<div id='D" + hora + txtMin +"' style='cursor:pointer' " + 
                        "onmouseover=\"$(this.id).setStyle('background','#7782a2')\" " + 
                        "onmouseout=\"$(this.id).setStyle('background','#ffffff')\" " + 
                        "onclick=\"$('" + el.id + "').value='" + ( i < 10 ? '0' + i : i ) + ":" + txtMin +  "';$('" + id + "').remove();\" " +
                        ">" + hora + ":" + txtMin + " " + meridiano + " " + tmpH + "</div>";
            }
        }
    }

    $( id ).setHTML(cad);
    setTimeout( "showOver('" + id + "');", 100 );
}
/**
 *  regresa el codigo de la tecla presionada por el usuario
 */
function kPress( evnt, id )
{
    code = ( window.ie ? evnt.keyCode : evnt.which );
    return code;
}
/**
 *  remueve elemento
 *  checar vigencia
 */
function hideClock()
{
    if( $( 'tmpDiv' ) )
    {
        $( 'tmpDiv' ).remove();
    }
}
/**
 *  Muestra el calendario para seleccionar fecha  asignar a input
 */
function showInputCalendar( id, date )
{
    if( arguments[ 2 ] )
    {
        evn = arguments[ 2 ];
        var Xpos = evn.clientX;
        var Ypos = evn.clientY;
    }
    var CAL = new Element( "div", { "id" : "selectCalandar" } ).inject( document.body );
    var aja = new Ajax( urlProcesos,
        {   'method'    :   'get',
            'data'      :   {'action':'showInputCalendar','date':date,'inputId' : id},
            'update'    :   $( 'selectCalandar' ),
            'onComplete':   function()
            {
                $( 'selectCalandar' ).setStyles(
                    {   'position'  :   'absolute',
                        'top'       :   ( Ypos ? Ypos - 20 : $( id ).getPosition().y.toInt() ) - 100 + 'px',
                        'left'      :   ( Xpos ? Xpos - 100 : $( id ).getPosition().x.toInt() ) - 100 + 'px'
                    }
                );
                showOver( 'selectCalandar' );
            }
        }
    ).request();
}
/**
 * 
 */
function elementRemove( id, time )
{
}
/*****************************************************************************************
 * MENSAJES Y ALERTAS
 * ***************************************************************************************/
/**
 *  marcha los checkbox para los destinatarios de mensajes
 */
function switchAll( el, tipo )
{
    var chk = $$( 'input.user_tipo_' + tipo );
    for( var i = 0; i < chk.length; i++ )
    {
        chk[i].checked = el.checked;
    }
}
/**
 *  Marca la alerta como revisada
 */
function alertaOK( alerta_id )
{
	if( confirm( "Marcar alerta como atendida?" ) == true )
	{
		var J = new Json.Remote( urlProcesos + "&action=alertOK&alerta_id=" + alerta_id,
			{	'onComplete' : function( obj )
				{
					if( obj.complete == 'ok' )
					{
						updateAlertList();
					}
					else
					{
						alert('error');
					}
				}
			}
		).send();
	}
}
/**
 *  Actualiza la lista de aleras
 */
function updateAlertList()
{
    if( $( 'alertasContenedor' ) )
    {
	    var aja = new Ajax( urlProcesos,
		    {	'method' : 'get',
    			'data'	: {'action' : 'updateAlertList'},
	    		'update' : $( 'alertasContenedor' )
		    }
    	).request();
    }
}
/**
 *  Actualiza el mensaje
 */
function updateMsjList()
{
    if( $( 'mensajesContenedor') )
    {
	    var aja = new Ajax( urlProcesos,
            {   'method' : 'get',
                'data' : {'action':'updateMsjList'},
                'update' : $( 'mensajesContenedor')
            }
        ).request();
    }
}
/**
 *  Guarda el mensaje capturado
 */
function saveMsj()
{
    if( $( 'paraTodos' ).checked == false && $( 'paraVarios' ).checked == false )
    {
        alert( 'Seleccione si el mensaje es para todos o para uno o varios usuarios' );
        return false;
    }
    if( $( 'paraVarios' ).checked == true )
    {
        var usr = false;
        var chk = $$( 'input.user_tipo_1','input.user_tipo_2','input.user_tipo_3','input.user_tipo_4');
        for( var i = 0; i < chk.length; i++ )
        {
            usr = chk[i].checked == true ? true : usr;
        }
        if( usr == false )
        {
            alert( 'necesita seleccionar por lo menos un usuario' );
            return false;
        }
    }
    if( $( 'mensaje_asunto' ).value == '' )
    {
        alert( 'se requiere de un asunto para registrar el mensaje' );
        return false;
    }
    var aja = new Ajax( urlProcesos,
        {   'method' : 'get',
            'data' : $( 'mensajesForm' ),
            'update' : $( 'mensajesContenedor'),
            'onComplete' : function()
            {
                $( 'captura_mensaje_alerta' ).remove();
            }
        }
    ).request();
}
/**
 *  Detalle del mensaje seleccionado
 */
function mensaje_detalle( mensaje_id )
{
    if( $(' detalle_mensaje' ) )
    {
        $( 'detalle_mensaje' ).remove();
    }
    var pos = getAvailablePosition();
    var Div = new Element( "div", { "id" : "detalle_mensaje" }).inject( document.body );
    $( 'detalle_mensaje' ).setStyles(
        {   'position'  :   'absolute',
            'top'       :   pos.y + 'px',
            'left'      :   pos.x + 'px'
        }
    );
    var aja = new Ajax( urlProcesos,
        {
            'method'    :   'get',
            'data'      :   {   'action' : 'mensaje_deta',
                                'mensaje_id' : mensaje_id
                            },
            'update'    :   $( "detalle_mensaje" ),
            'onComplete'    : function()
            {
                showOver( "detalle_mensaje" );
            }
        }
    ).request();
}
/**
 *  Nuevo mensaje
 */
function nuevo_mensaje()
{
    captura_ma_form( 'mensaje' );
}
/**
 *  formulario para la captura de mensajes
 */
function captura_ma_form( tipo )
{
    if( $( 'captura_mensaje_alerta' ) )
    {
        $( 'captura_mensaje_alerta' ).remove();
    }
    var pos = getAvailablePosition();
    var Div = new Element( "div",{"id" : "captura_mensaje_alerta"} ).inject( document.body );
    $( 'captura_mensaje_alerta' ).setStyles(
        {   'position'  :   'absolute',
            'left'      :   pos.x + 'px',
            'top'       :   pos.y + 'px'
        }
    );
    var aja = new Ajax( urlProcesos,
        {
            'method'        :   'get',
            'data'          :   {   'action'    : 'form_cap_mensaje_alerta',
                                    'tipo'      :   tipo
                                },
            'update'        :   $( 'captura_mensaje_alerta' ),
            'onComplete'    :   function()
            {
                showOver( 'captura_mensaje_alerta' );
            }
        }
    ).request();
}
/**
 * LOOP de funciones
*/
function loopFunctions()
{
    chkComments();
	updateAlertList();
	updateMsjList();
    chkInvita();
	//setTimeout( "loopFunctions()", 60000 );
    if( arguments[ 0 ] )
    {
        setCascade();
    }
	setTimeout( "loopFunctions()", 60000 );
}
/**
 * Buscador de tareas
 */
function buscador( el )
{
    if( !$( 'searchRS' ) )
    {
        var srs = new Element( "div", { "id" : "searchRS" } ).inject( document.body );
    }
    if( el.value.length >= 3 )
    {
        var aja = new Ajax( urlProcesos,
            {   'method' : 'get',
                'data'   : {'action':'seachData','valor' : el.value },
                'update' : $( 'searchRS' ),
                'onComplete' : function()
                {
                    $( 'searchRS' ).setStyles( 
                        {
                            'position'  : 'absolute',
                            'top'       :   $( el.id ).getPosition().y + 20,
                            'left'      :   $( el.id ).getPosition().x
                        }
                    );
                    showOver( 'searchRS');
                }
            }
        ).request();
    }
    else
    {
        $( 'searchRS' ).remove();
    }
}
/**
 *  Asigna el status de la solicitud recibida
 *  0   pendiente de confirmacion
 *  1   Aceptada
 *  2   Resolucion mas tarde
 *  3   No acptada
 */
function setSolicitudStatus( acti_id, status )
{
    var jsn = new Json.Remote( 
        urlProcesos + '&action=set_solicitud_status' + 
        '&acti_id=' + acti_id + '&status=' + status,
        {   'onComplete'    :   function( obj )
            {
                if( obj.complete == 'ok' )
                {
                    if( $( 'acti_fech_hidden' ) )
                    {
                        show_activities( $( 'actiFechHidden' ).value );
                        $('acti_deta_div').remove();
                    }
                    else
                    {
                        activitie_deta( obj.acti_id );
                    }
                    chkInvita();
                }
            }
        }
    ).send();
}
/**
 *  Filtra listado de recursos humanos
 */
function filtraRecursosHumanos( val )
{
    filtraUserList( val, 'listaRecursosHumanos','add_recu_huma', 'ALL' );
}
/**
 *  Filtra listado de usuarios
 */
function filtraUserList( val, idUpdate, functionName, filterType )
{
    var obj=   {
            'val'           :   val,
            'idUpdate'      :   idUpdate,
            'functionName'  :   functionName,
            'filterType'    :   filterType,
            'action'        :   'filter_user_list'
        }
    if( arguments[4] )
    {
        obj.tipo = arguments[ 4 ];
    }
    filterList( obj );
}
/**
 * Filtra listado de clientes
 */
function filtraClientList( val, idUpdate, functionName )
{
    filterList( { 'val' : val, 'idUpdate' : idUpdate, 'functionName' : functionName, 'action' : 'filter_client_list' } );
}
/**
 *  Filtra listado
 */
function filterList( obj )
{
    var filter = false;
    var tipo   = ( obj.tipo ? obj.tipo : '' );
    var filter = ( obj.val.length >= 2 ? obj.val : '' );

    var aja = new Ajax( urlProcesos,
        {   'method'    :   'get',
            'data'      :   {   'action'        :   obj.action,
                                'functionName'  :   obj.functionName,
                                'filterType'    :   obj.filterType ? obj.filterType : 'USER',
                                'filter'        :   filter,
                                'tipo'          :   tipo
                            },
            'update'    :   $( obj.idUpdate )
        }
    ).request();
}
/**
 *  Abre listado de usuarios
 */
function openUserList()
{
    if( $( 'recuHumaDiv' ) ) $( 'recuHumaDiv' ).remove();
    var pos = getAvailablePosition();
    var DIV = new Element( 'div', { 'id' : 'recuHumaDiv' } ).inject( document.body );

    $( 'recuHumaDiv' ).setStyles(
        {
            'position'  :   'absolute',
            'top'       :   pos.y + 'px',
            'left'      :   pos.x + 'px'
        }
    );
    
    var axa = new Ajax( urlProcesos,
        {   'method'    :   'get',
            'data'      :   { 'action' : 'get_recu_huma_list' },
            'update'    :   $( 'recuHumaDiv' ),
            'onComplete': function() { showOver( 'recuHumaDiv' ); }
        }
    ).request();
}
/**
 *  
 */
function chkRecuHuma( acti_id )
{
    recuHumaArr = [];
    var json = new Json.Remote( urlProcesos + '&action=chkRecuHuma&acti_id=' +acti_id,
        {   'onComplete'    :   function( jsonObj )
                                {
                                    for( var i = 0; i < jsonObj.recuHumaArr.length; i++ )
                                    {
                                        add_recu_huma( 'user_' + jsonObj.recuHumaArr[i] );
                                    }
                                }
        }
    ).send();
}
/**
 *  Elimina el recurso humano seleccionado de la lista
 */
function removeRecuHuma( id )
{
    $( 'acti_recu_huma' + id ).remove();
    var tmpArr = [];
    for( var i=0; i < recuHumaArr.length; i++ )
    {
        if( id != recuHumaArr[ i ] )
        {
            tmpArr.include( recuHumaArr[ i ] );
        }
    }
    recuHumaArr = tmpArr;
}
/** 
 *  Abre el listado de recursos humanos
 */
function add_recu_huma( user_id )
{
    if( $( 'listaRecuHumaDiv' ) )
    {
        var url = urlProcesos + "&action=get_user_obj&user_id=" + user_id.split("_").pop();
        var json = new Json.Remote( url,
        {   'onComplete' : function( obj )
            {
                if( obj.complete == 'ok' )
                {
                    recuHumaArr.include( obj.user_id );
                    if( $( 'acti_recu_huma' + obj.user_id ) )
                    {
                        $( 'acti_recu_huma' + obj.user_id ).remove();
                    }

                    var div1 = new Element( 'div',
                        {
                            'id'        :   'acti_recu_huma' + obj.user_id,
                            'styles'    :   {   'border-bottom' :   'solid 1px #cdcdcd',
                                                'height'        :   '15px',
                                                'white-space'   :   'nowrap',
                                                'cursor'        :   'pointer'
                            },
                            'events'    :   {
                                'click' :   function()
                                { 
                                    removeRecuHuma( obj.user_id )
                                }
                            }
                        }
                    ).inject( $('listaRecuHumaDiv') );

                    var html =  "<img src='img/themes/" + obj.theme + "/iconos/menos.png' align='top'/>" +
                                obj.user_nombre;
                    $( 'acti_recu_huma' + obj.user_id ).setHTML( html );
                }
                else
                {
                    alert( 'error' );
                }
            }
        }
        ).send();
    }
    else
    {
        $( 'recuHumaDiv' ).remove();
    }
}
/**
 *  Abre el panel de disponibilidad de horarios de los recursos humanos
 */
function chkHorarios()
{
    selectHour = {'stat':0,'h1':0,'h2':0};
    if( $( 'chkHorariosDiv' ) ) $( 'chkHorariosDiv' ).remove();
    var pos = getAvailablePosition();
    if( recuHumaArr.length > 0 )
    {
        var DIV = new Element( 'div',
            {   'id'    :   'chkHorariosDiv',
                'styles'    :   {
                    'position'  : 'absolute',
                    'top'       :   pos.y + 'px',
                    'left'      :   pos.x + 'px'
                }
            }
        ).inject( document.body );
        var aja = new Ajax( urlProcesos,
            {   'method'    :   'get',
                'data'      :   {   'action'    :   'chk_horarios',
                                    'fecha'     :   arguments[0] ? arguments[0] : $( 'acti_fech_fin' ).value,
                                    'usuarios'  :   recuHumaArr 
                                },
                'update'    :   $( 'chkHorariosDiv' ),
                'onComplete'    :   function()
                {
                    showOver( 'chkHorariosDiv' );
                }
            }
        ).request();
    }
    else
    {
        alert( 'Necesita agreagr recursos humanos para checar la disponibilidad de horarios');
    }
}
/**
 * selecciona los horarios en el panel de disponibilidad de recursos humanos
 */
function selectHorarios(obj)
{
    if( obj.freeRow == 'NO' )
    {
        var continua = confirm( 'Algun usuario tiene registrada una tarea en esta hora\ndesea continuar?' );
    }
    else
    {   
        var continua = true;
    }
    if( continua == true )
    {
        selectHour.stat++;
        /**
         *  Primer click asigna hora inicial
         */
        if( selectHour.stat == 1 )
        {
            /**
             *  Regresando color de fondo original
             */
            for( var i = obj.hini.toInt(); i <= obj.hfin.toInt(); i++ )
            {
                var currBG = $( 'trH_' + i ).getStyle( 'background-color' );
                if( currBG != '#f4eaea' )
                {   
                    $( 'trH_' + i ).setStyle( 'background-color' , '#ffffff' );
                }
            }
            selectHour.h1 = obj.hora;
            if( $( 'trH_' + obj.hora ).getStyle( 'background-color' ) != '#f4eaea' )
            {
                $( 'trH_' + obj.hora ).setStyle('background-color' , '#b1bda2');
            }
            $( 'acti_hora_ini_sel' ).value = ( selectHour.h1.toInt() < 10 ? '0' : '' ) + selectHour.h1 + ':00';
            $( 'acti_hora_fin_sel' ).value = ( selectHour.h1.toInt() < 10 ? '0' : '' ) + selectHour.h1 + ':59';
        }
        /**
         *  Segundo click pinta filas de la hora inicial a la hora final
         */
        if( selectHour.stat == 2 )
        {
            if( $( 'trH_' + obj.hora ).getStyle( 'background-color' ) != '#f4eaea' )
            {
                $( 'trH_' + obj.hora ).setStyle('background-color' , '#b1bda2');
            }
            /**
             *  Ordenando las horas seleccionadas de menor a mayor
             */
            if( obj.hora.toInt() < selectHour.h1.toInt() )
            {
                var horaIni =  obj.hora;
                var horaFin =  selectHour.h1;
                selectHour.h1 = horaIni;
                selectHour.h2 = horaFin;
            }
            else
            {
                selectHour.h2 = obj.hora;
            }
            /**
             *  Pintando filas seleccionadas
             */
            var free = true;
            for( var i = selectHour.h1.toInt(); i <= selectHour.h2.toInt(); i++ )
            {
                var currBG = $( 'trH_' + i ).getStyle( 'background-color' );
                if( currBG != '#f4eaea' )
                {   
                    $( 'trH_' + i ).setStyle( 'background-color' , '#d4e5d0' );
                }
                free = ( $('trH_' + i ).hasClass( 'ocupada' ) ? false : free );
            }
            if( free == false )
            {
                alert( 'Selecciono un horario con algunas horas ocupadas por otros usuarios' );
            }
            $( 'acti_hora_ini_sel' ).value = ( selectHour.h1.toInt() < 10 ? '0' : '' ) + selectHour.h1 + ':00';
            $( 'acti_hora_fin_sel' ).value = ( selectHour.h2.toInt() < 10 ? '0' : '' ) + selectHour.h2 + ':59';
            selectHour = {'stat':0,'h1':0,'h2':0};
        }
    }
}
/**
 *  asigna el horario y la fecha desde el panel de disponibilidad de recursos humanos
 */
function setHorario()
{
    if( $('acti_fech_fin') && $('acti_fech_fin_sel').value != '' ) $('acti_fech_fin').value=$('acti_fech_fin_sel').value;
    if( $('acti_hora_ini') && $('acti_hora_ini_sel').value != '' ) $('acti_hora_ini').value=$('acti_hora_ini_sel').value;
    if( $('acti_hora_fin') && $('acti_hora_fin_sel').value != '' ) $('acti_hora_fin').value=$('acti_hora_fin_sel').value;
    /**
     *  Si no se selecciona hora final toma hora inicial + ':59' para la hora final
     */
    if( $('acti_hora_fin_sel').value == '' )
    {
        if( selectHour.h1 )
        {
            $('acti_hora_ini').value = ( selectHour.h1.toInt() < 10 ? '0' : '' ) + selectHour.h1 + ':00';
            if( selectHour.h2.toInt() <= 0 )
            {
                $('acti_hora_fin').value = ( selectHour.h1.toInt() < 10 ? '0' : '' ) + selectHour.h1 + ':59';
            }
            else
            {
                $('acti_hora_fin').value = ( selectHour.h2.toInt() < 10 ? '0' : '' ) + selectHour.h2 + ':59';
            }
        }
    }
    $('chkHorariosDiv').remove(); 
}
/**
 *  Monitor de usuarios
 */
function userMonitor()
{
    $( 'userMonitorDiv' ).setStyles(
        {
            'display'   :   'block',
            'width'     :   '250px',
            'height'    :   '610px',
            'overflow'  :   'hidden'
        }
    );
    var ajx = new Ajax( urlProcesos,
        {   'method'    :   'get',
            'data'      :   { 'action' : 'get_user_monitor'},
            'update'    :   $('userMonitorDiv')
        }
    ).request();
}
/**
 * abre una nueva ventana con la vista del usuario seleccionado del monitor
 */
function openUserMonitor( sid )
{
    window.open( "index.php?SID=" + sid , "", "width=1150, height=620" );
}
/**
 *  Buscando posiciones disponibles
 */
function getAvailablePosition()
{
    var ini = initPosition();
    var available = ini;
    var cant = ventanasEmergentes.length;
    var margen = rango * cant;
    var margenY =   ini.y + margen;
    var margenX =   ini.x + margen;
    for( var i = 0; i < cant; i++ )
    {   
        if( $( ventanasEmergentes[ i ] ) )
        {
            var elPos   =   $( ventanasEmergentes[ i ] ).getPosition();
            var elX     =   elPos.x.toInt();
            var elY     =   elPos.y.toInt();
            //if( elX > ( ini.x - rango ) && elX < margenX )
            //{
                available.x += rango;
            //}
            //if( elY > ( ini.y - rango ) && elY < margenY  )
            //{
                available.y += rango;
            //}
        }
        
    }
    return available;
}
/**
 *  Ordena ventanas emergentes abiertas en carcada
 */
function setCascade()
{
    var ini = initPosition();
    var win = ventanasEmergentes;
    var cant = 1;
    for( var i = 0; i < win.length; i++ )
    {
        if( $( win[ i ] ) )
        {
            $( win[ i ] ).setStyles(
                {   'position'  :   'absolue',
                    'top'       :   ( ini.y + ( rango * cant ) ) + 'px',
                    'left'      :   ( ini.x + ( rango * cant ) ) + 'px'
                }
            );
            cant++;
        }
    }
}
/**
 *  cierra todas las ventanas emergentes
 */
function closeAllWindows()
{
    for( var i = 0; i < ventanasEmergentes.length; i++ )
    {
        if( $( ventanasEmergentes[ i ] ) )
        {
            $( ventanasEmergentes[ i ] ).remove();
        }
    }
}

