<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php

function encabezado2($target) {
    if (!empty($target))
        $onload = "onload='javascript:document.backup." . $target . ".focus()'";
    ?>
    <script language="JavaScript">

        function mensaje_demora() {
            alert("Este proceso es demorado, Porfavor sea paciente!!!!\n\n");
        }

        function confirmEst(est) {
            var supr1;
            if (est == 'Eliminar')
                supr1 = confirm("Realmente desea eliminar los registros? ");
            if (est == 'Actualizar')
                supr1 = true;
            if (supr1 == true) {
                return true;
            } else {
                return false;
            }
        }

        function checkAll() {
            for (var j = 1; j <= 14; j++) {
                box = eval("document.checkboxform.c");
                if (box.checked == false)
                    box.checked = true;
            }
        }


        function rusure() {
            question = confirm("Esta seguro que desea eliminar")
            if (question != "0") {
                self.location = ""
            }
        }

        function validarforma()
        {
            var i, p, q, nm, test, num, min, max, errors = '', args = validarforma.arguments;
            for (i = 0; i < (args.length - 2); i += 3)
            {
                test = args[i + 2];
                val = MM_findObj(args[i]);
                if (val)
                {
                    nm = val.name;
                    if ((val = val.value) != "")
                    {
                        if (test.indexOf('isEmail') != -1)
                        {
                            p = val.indexOf('@');
                            if (p < 1 || p == (val.length - 1))
                                errors += '- ' + nm + ' must contain an e-mail address.\n';
                        }
                        else if (test != 'R')
                        {
                            num = parseFloat(val);
                            if (isNaN(val))
                                errors += '- ' + nm + ' must contain a number.\n';
                            if (test.indexOf('inRange') != -1)
                            {
                                p = test.indexOf(':');
                                min = test.substring(8, p);
                                max = test.substring(p + 1);
                                if (num < min || max < num)
                                    errors += '- ' + nm + ' must contain a number between ' + min + ' and ' + max + '.\n';
                            }
                        }
                    }
                    else if (test.charAt(0) == 'R')
                        errors += '-> ' + nm + ' es Requerido.<-\n';
                }
            }
            if (errors)
                alert('Hay Algunos Campos Requeridos:\n\n' + errors);
            document.MM_returnValue = (errors == '');
        }


        function MM_swapImgRestore() { //v3.0
            var i, x, a = document.MM_sr;
            for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
                x.src = x.oSrc;
        }

        function MM_preloadImages() { //v3.0
            var d = document;
            if (d.images) {
                if (!d.MM_p)
                    d.MM_p = new Array();
                var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
                for (i = 0; i < a.length; i++)
                    if (a[i].indexOf("#") != 0) {
                        d.MM_p[j] = new Image;
                        d.MM_p[j++].src = a[i];
                    }
            }
        }

        function MM_findObj(n, d) { //v4.0
            var p, i, x;
            if (!d)
                d = document;
            if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
                d = parent.frames[n.substring(p + 1)].document;
                n = n.substring(0, p);
            }
            if (!(x = d[n]) && d.all)
                x = d.all[n];
            for (i = 0; !x && i < d.forms.length; i++)
                x = d.forms[i][n];
            for (i = 0; !x && d.layers && i < d.layers.length; i++)
                x = MM_findObj(n, d.layers[i].document);
            if (!x && document.getElementById)
                x = document.getElementById(n);
            return x;
        }

        function MM_swapImage() { //v3.0
            var i, j = 0, x, a = MM_swapImage.arguments;
            document.MM_sr = new Array;
            for (i = 0; i < (a.length - 2); i += 3)
                if ((x = MM_findObj(a[i])) != null) {
                    document.MM_sr[j++] = x;
                    if (!x.oSrc)
                        x.oSrc = x.src;
                    x.src = a[i + 2];
                }
        }


    </script>
    <?
    echo"<html>";
    echo"<head>";
    echo"<title>.:: WEBSIM GAMA ::. </title>";
    echo"<meta name=\"author\" content='DESARROLLO WEB'>";
    echo"<link rel='stylesheet' href='css/style.css' type=\"text/css\">";
    echo"<link rel=\"SHORTCUT ICON\" href=imagenes/icon_gamma.gif>";
    echo"</head>";
    echo"<body " . $onload . " leftmargin=\"0\" topmargin=\"0\" marginheight=\"0\" marginwidth=\"0\" bgcolor=\"#ffffff\" >";
}

//FIN DEL ENCABEZADO 2

function encabezado($target) {
    if (!empty($target))
        $onload = "onload='javascript:document.backup." . $target . ".focus()'";
    ?>
    <script language="JavaScript">
    <!--

        function mensaje_demora()
        {
            alert("Este proceso es demorado, Porfavor sea paciente!!!!\n\nCARPEDIEM COLMBIA");
        }


        function checkAll() {
            for (var j = 1; j <= 14; j++) {
                box = eval("document.checkboxform.c");
                if (box.checked == false)
                    box.checked = true;
            }
        }

        function rusure() {
            question = confirm("Esta seguro que desea eliminar")
            if (question != "0") {
                self.location = ""
            }
        }

        function validarforma()
        {
            var i, p, q, nm, test, num, min, max, errors = '', args = validarforma.arguments;
            for (i = 0; i < (args.length - 2); i += 3)
            {
                test = args[i + 2];
                val = MM_findObj(args[i]);
                if (val)
                {
                    nm = val.name;
                    if ((val = val.value) != "")
                    {
                        if (test.indexOf('isEmail') != -1)
                        {
                            p = val.indexOf('@');
                            if (p < 1 || p == (val.length - 1))
                                errors += '- ' + nm + ' must contain an e-mail address.\n';
                        }
                        else if (test != 'R')
                        {
                            num = parseFloat(val);
                            if (isNaN(val))
                                errors += '- ' + nm + ' must contain a number.\n';
                            if (test.indexOf('inRange') != -1)
                            {
                                p = test.indexOf(':');
                                min = test.substring(8, p);
                                max = test.substring(p + 1);
                                if (num < min || max < num)
                                    errors += '- ' + nm + ' must contain a number between ' + min + ' and ' + max + '.\n';
                            }
                        }
                    }
                    else if (test.charAt(0) == 'R')
                        errors += '-> ' + nm + ' es Requerido.<-\n';
                }
            }
            if (errors)
                alert('Hay Algunos Campos Requeridos:\n\n' + errors);
            document.MM_returnValue = (errors == '');
        }


        function MM_swapImgRestore() { //v3.0
            var i, x, a = document.MM_sr;
            for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
                x.src = x.oSrc;
        }

        function MM_preloadImages() { //v3.0
            var d = document;
            if (d.images) {
                if (!d.MM_p)
                    d.MM_p = new Array();
                var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
                for (i = 0; i < a.length; i++)
                    if (a[i].indexOf("#") != 0) {
                        d.MM_p[j] = new Image;
                        d.MM_p[j++].src = a[i];
                    }
            }
        }

        function MM_findObj(n, d) { //v4.0
            var p, i, x;
            if (!d)
                d = document;
            if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
                d = parent.frames[n.substring(p + 1)].document;
                n = n.substring(0, p);
            }
            if (!(x = d[n]) && d.all)
                x = d.all[n];
            for (i = 0; !x && i < d.forms.length; i++)
                x = d.forms[i][n];
            for (i = 0; !x && d.layers && i < d.layers.length; i++)
                x = MM_findObj(n, d.layers[i].document);
            if (!x && document.getElementById)
                x = document.getElementById(n);
            return x;
        }

        function MM_swapImage() { //v3.0
            var i, j = 0, x, a = MM_swapImage.arguments;
            document.MM_sr = new Array;
            for (i = 0; i < (a.length - 2); i += 3)
                if ((x = MM_findObj(a[i])) != null) {
                    document.MM_sr[j++] = x;
                    if (!x.oSrc)
                        x.oSrc = x.src;
                    x.src = a[i + 2];
                }
        }
    //-->
    </script>
    <?php
    echo"<html>";
    echo"<head>";
    echo"<title>.:: WEBSIM GAMMA ::.</title>";
    ?>
    <style type="text/css">
        body { font-family: verdana, arial, helvetica, sans-serif;
               font-size: 12px; }
        h1 { font-size:1.3em }	
        a:link, a:visited { color:#339 }	
        div#rolltipDiv {
            position:absolute; visibility:hidden;
            left:0; top:0; z-index:1000;
            width:105px; height:30px; padding:3px; font-size:11px;
            background:url("imagenes/ToolTips.gif") #ffffff; border:1px solid #336; 
        }

    </style>
    <style>
        .thdrcell {
            background:#F3F0E7;
            font-family:arial;
            font-size:12px;
            font-weight:bold;
            padding:5px;
            border-bottom:1px solid #C8BA92;
        }

        .tdatacell {
            font-family:arial;
            font-size:12px;
            padding:5px;
            background:#FFFFFF
        }

        .dvhdr1 {
            background:#F3F0E7;
            font-family:arial;
            font-size:12px;
            font-weight:bold;
            border:1px solid #C8BA92;
            padding:5px;
            width:103px;
            height:30px;
        }

        .dvbdy1 {
            background:url("imagenes/ToolTips.gif");
            font-family:arial;
            font-size:12px;
            font-weight:bold;
            text-align: center;
            text-valign: middle;
            border-left:1px solid #308DC7;
            border-right:1px solid #308DC7;
            border-bottom:1px solid #308DC7;
            border-top:1px solid #308DC7;
            padding:5px;
            width:103px;
            height:30px;
        }

        p {
            margin-top:20px;
        }

        h1 {
            font-size:13px;
        }

        .dogvdvhdr {
            width:300;
            background:#C4D5E3;
            border:1px solid #C4D5E3;
            font-weight:bold;
            padding:10px;
        }

        .dogvdvbdy {
            width:300;
            background:#FFFFFF;
            border-left:1px solid #C4D5E3;
            border-right:1px solid #C4D5E3;
            border-bottom:1px solid #C4D5E3;
            padding:10px;
        }

        .pgdiv {
            width:320;
            height:250;
            background:#E9EFF4;
            border:1px solid #C4D5E3;
            padding:10px;
            margin-bottom:20;
            font-family:arial;
            font-size:12px;
        }
    </style>
    <script type="text/javascript">

        function showRollTip(msg, e) {
            RollTip.reveal(msg, e);
        }
        function hideRollTip() {
            RollTip.conceal();
        }
    </script>
    <script language="javascript">
        function toggle(id) {
            //
            //$id.=" Mas";
            obj = document.getElementById(id);
            if (obj.style.display == "") {
                obj.style.display = "none"
            }
            else {
                obj.style.display = ""
            }

        }
    </script>
    <script>
        function addOpt(oCntrl, sTxt, sVal, sCnd) {
            if (sTxt.substr(0, sCnd.length).toUpperCase() == sCnd.toUpperCase()) {
                var selOpcion = new Option(sTxt, sVal);
                eval(oCntrl.options[i++] = selOpcion);
            }
        }

        function cambia(origen, control) {
            oCntrl = document.getElementById(control);
            arreglo = oCntrl.valores;
            var txtVal = origen.value;
            while (oCntrl.length > 0)
                oCntrl.options[0] = null;
            i = 0;
            oCntrl.clear;

            for (k = 0; k < arreglo.length; k++)
            {
                addOpt(oCntrl, arreglo[k][0], arreglo[k][1], txtVal);
            }

        }

        function carga(control)
        {
            oCntrl = document.getElementById(control);
            oCntrl.valores = Array();
            arreglo = oCntrl.valores;
            for (i = 0; i < oCntrl.length; i++)
            {
                arreglo[i] = Array();
                arreglo[i][0] = oCntrl[i].text;
                arreglo[i][1] = oCntrl[i].value;
            }
        }

        function confirmDel() {
            var supr;
            supr = confirm("Realmente desea eliminar los registros? ");
            if (supr == true) {
                return true;
            } else {
                return false;
            }
        }

        function Numerico(evt) {
            var charCode = (evt.which) ? evt.which : evt.keyCode//c�digo de tecla.
            //alert(charCode);
            if ((charCode < 48 || charCode > 57) && (charCode < 9 || charCode > 9) && (charCode < 8 || charCode > 8) && (charCode < 37 || charCode > 40) && (charCode < 45 || charCode > 46) && (charCode < 11 || charCode > 11)) {//si no es n�mero.
                return false;
            }
        }
    </script>
    <?
    echo"<meta name=\"author\" content='DESARROLLO WEB'>";
    echo"<link rel='stylesheet' href='css/style.css' type=\"text/css\">";
    echo"<link rel=\"SHORTCUT ICON\" href=imagenes/icon_gamma.gif>";
    echo"</head>";
    echo"<body " . $onload . " leftmargin=\"0\" topmargin=\"0\" marginheight=\"0\" marginwidth=\"0\" bgcolor=\"#ffffff\" >";
    $Fecha = date('d-m-Y');
    $Hora = date('H:i:s');
    ?>
    <center><table width="1004" height="101" border="0" cellpadding="0" cellspacing="0">
            <tbody><tr>
                    <td background="imagenes/baner.jpg"></td>
                </tr>
            </tbody></table></center></div>
    <br>
    <?php
    echo"<center>";
    echo"<center><table border=0 width=1004 cellspacing=0>";
    echo"<tr>";
    echo"<td width=21% background=\"imagenes/bg2.jpg\" valign=top class='titulo'>Usuario: " . $_SESSION['nombre_usuario'];
    echo "<br>Perfil: " . $_SESSION['perfil_usuario'];
    if ($_SESSION['perfil'] == '5') {
        echo "<br>Cliente: " . $_SESSION['nombre_cliente'];
    }

    echo "<br>Fecha: " . $Fecha . " Hora:" . $Hora;
}
?>

<?php

function menu($id_user) {
    $conn = mysql_connect("localhost", "root", "+cOlOmbIA-");
    $sql_menu_titulo = "SELECT * FROM menu_usuario AS a INNER JOIN menu AS b ON a.id_menu=b.id where id_usuario='" . $id_user . "'";
    $rst_menu_titulo = mysql_query($sql_menu_titulo, $GLOBALS["v_mysql"]);
    $row = mysql_num_rows($rst_menu_titulo);
    echo"<TABLE width=90%>";
    echo "<TR class=miTable_tr>";
    echo "<TD class=miTable_Titulo>Sistema WEBSIM GAMMA</TD>";
    echo "</TR>";
    while ($row_menu_titulo = mysql_fetch_array($rst_menu_titulo)) {
        echo "<TR class=miTable_tr><TH class=miTable_th1>" . $row_menu_titulo['nombre'] . "</TH></TR>";
        $id_menu = $row_menu_titulo['id_menu'];
        //submenu($id_menu);
        $sql_idmenu = "SELECT * FROM menu_dinamico WHERE id_menu='" . $id_menu . "'";
        $rst_idmenu = mysql_query($sql_idmenu, $GLOBALS["v_mysql"]);
        while ($rows_idmenu = mysql_fetch_array($rst_idmenu)) {
            echo "<TR class=miTable_tr><TD class=miTable_td><a href='" . $rows_idmenu['script'] . "?id_user=$id_user' class=sublevel>" . $rows_idmenu['funcionalidad'] . "</a></TD></TR>";
        }
    }
    echo"<TR>";
    echo"<TH><a href=\"index.php\"><font color=#0143A7><div align=right><img src=imagenes/recursos/eliminar.png border=0><font class=titulo6>&nbsp;Salir</div></font></a></TH>";
    echo"</TR>";
    echo"</TABLE>";
}

//include_once ("conex.php");
function conn_mysql() {
    include("./conexion2.php");
    if (!($link = @mysql_pconnect($dbhost, $dbusuario, $dbpassword))) {
        echo"Error Conectando Con La BD. " . mysql_error();
        exit();
    }
    if (!mysql_select_db($db, $link)) {
        echo"Error Seleccionando La BD. " . mysql_error();
    }
    return $link;
}

$v_mysql = conn_mysql();

function submenu($id_menu) {
    
}

function mostrar_cabeza_trabajo($nombrepagina) {
    $sql_logo = "SELECT logo FROM info_empresa";
    $rst_logo = mysql_query($sql_logo, $GLOBALS["v_mysql"]);
    $logo = mysql_fetch_array($rst_logo);
    echo "<center>";
    echo "<table width='95%' border=0 cellspacing=0>";
    echo "<TR>";
    echo "<TD><font class=titulo6><img src='imagenes/icon_gamma.gif' border=0>" . $nombrepagina . "</font></TD>";
    echo "<td><div align=right><img src='logos/" . $logo[0] . "' border=0></th>";
    echo "</tr>";
    echo "</table>";
    echo "</center>";
}

function mostrar_pie() {
    $sql_info = "SELECT * FROM info_empresa";
    $resultado = mysql_query($sql_info, $GLOBALS["v_mysql"]);
    $row_get_datos = mysql_fetch_array($resultado);

    echo"<TR>";
    echo"<TD>";
    echo"</TD>";
    echo"<TD background=imagenes/bg.jpg colspan='2'>";
    echo "<center>";
    echo "<table width='90%' border='0'>";
    echo "<tr class=miTable_tr >";
    echo "<th class=miTable_th1 ><center><font size=1>$row_get_datos[1], Direccion: $row_get_datos[3] Bogota - Colombia - Telefonos: $row_get_datos[4] FAX: $row_get_datos[5] email: $row_get_datos[6]</font></center></th>";
    echo "</tr>";
    echo "</table>";
    echo "</center>";
    echo"</TD>";
    echo"</TR>";
}

function mostrar_pie_rastreo() {
    $sql_info = "SELECT * FROM info_empresa";
    $resultado = mysql_query($sql_info, $GLOBALS["v_mysql"]);
    $row_get_datos = mysql_fetch_array($resultado);

    echo"<TR>";
    echo"<TD background=imagenes/bg.jpg colspan='2'>";
    echo "<center>";
    echo "<table width='90%' border='0'>";
    echo "<tr class=miTable_tr >";
    echo "<th class=miTable_th1 ><center><font size=1>$row_get_datos[1], Direccion: $row_get_datos[3] Bogota - Colombia - Telefonos: $row_get_datos[4] FAX: $row_get_datos[5] email: $row_get_datos[6]</font></center></th>";
    echo "</tr>";
    echo "</table>";
    echo "</center>";
    echo"</TD>";
    echo"</TR>";
}

function pie_de_pagina() {
    ?>
    <style type="text/css">
        /*body {
            margin-left: 0px;
            margin-top: 0px;
            margin-right: 0px;
            margin-bottom: 0px;
            background-color:ffffff;
            background-image:url("imagen/fondo_pie.jpg");
            background-position: center center;    
            background-repeat: no-repeat;    
            background-size: 100% 100%;  
            -moz-background-size: 100% 100%;                
        }*/

        .miPie_Ti { /* Color de fondo de la columa para mostrar informacion*/
            font-family: Trebuchet MS, Verdana, Arial, Helvetica, sans-serif;
            font-size: 11px;
            font-weight:bold;
            text-indent:0px;
            color:#003366;
        }

        .miPie{ /*Propiedades de la tabla*/
            border-collapse: separate;
            border:#cccccc outset;
            font-size:10px;
            color:#666666;
        }

        .mipie_td { /* Color de fondo de la columa de la tabla general*/
            font-family: Trebuchet MS, Verdana, Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #003366;
            font-weight:bold;
            text-indent:0px;
            border:Gray ;
        }   
    </style>
    <TABLE align="center" border="0" width="90%">
        <td height="20" class="miPie_td" >
            <div align="center">                                    
                <TABLE align="center" border="0" width="100%">
                    <TR>
                        <TD align="center" class="miPie_Ti">www.carpediem.com.co</TD>
                    </TR>
                    <TR>
                        <TD align="center" class="miPie_Ti">&#174;Copyright 2013</TD>
                    </TR>
                </TABLE>
            </div>
    </TABLE>  
    <?
}

function combo_user($id, $sucur) {
    if ($sucur == 1) {
        $sqlm = "SELECT id_usuario, nombre FROM usuarios WHERE estado=1 and id_perfil!=5";
    } else {
        $sqlm = "SELECT id_usuario, nombre FROM usuarios WHERE estado=1 and id_perfil!=5 and  id_sucursal=$sucur";
    }
    $res = mysql_query($sqlm, $GLOBALS["v_mysql"]);

    echo '<select name="id" id="id" style="width:300px">
	<option value="">Seleccione un Usuario</option>';
    while ($id_u = mysql_fetch_assoc($res)) {
        echo "<option value='$id_u[id_usuario]' ";
        if ($id == $id_u['id_usuario'])
            echo "selected='selected'";
        echo ">$id_u[nombre]</option>";
    }
    echo '</select>';
}

function consultar_sql($sql) {
    $rs_con = mysql_query($sql, $GLOBALS["v_mysql"]);
    $nr = mysql_num_rows($rs_con);
    return $nr;
}

function logo($sql) {
    $rs = mysql_query($sql, $GLOBALS["v_mysql"]);
    $rt = mysql_result($rs, 0, 'logo');
    echo mysql_error();
    $ruta = '../logos/' . $rt;
    return $ruta;
}

function ip_pub($sql) {
    $rs = mysql_query($sql, $GLOBALS["v_mysql"]);
    $rt = mysql_result($rs, 0, 'ip_publica');
    echo mysql_error();
    $ip = 'http://' . $rt;
    return $ip;
}

function consul_planilla($id_mensajero) {
    $sql = "select coalesce(max(id_planilla),0) as id_pla from planillas where fecha_planilla='" . date('Y-m-d') . "' and id_mensajero=$id_mensajero";
    $rs = mysql_query($sql, $GLOBALS["v_mysql"]);
    $id_pla = mysql_result($rs, 0, 'id_pla');
    return $id_pla;
}

function max_planilla($id_mensajero) {
    $sql = "select coalesce(max(id_planilla),0) as id_pla from planillas where id_mensajero=$id_mensajero";
    $rs = mysql_query($sql, $GLOBALS["v_mysql"]);
    $id_pla = mysql_result($rs, 0, 'id_pla');
    return $id_pla;
}

function guias_reenvio($guia) {
    $sql = "select E16 from rastreo_guias where guia='" . $guia . "'";
    $rs = mysql_query($sql, $GLOBALS["v_mysql"]);
    
    $cur_res=mysql_fetch_array($rs);       
    $e16=$cur_res['E16'];
    if ($e16 == 16) {
        $ree = 1;
    } else {
        $ree = 0;
    }
    return $ree;
}

function sumaDia($fecha, $dia) { //SUMA LOS DIAS
    list($year, $mon, $day) = explode('-', $fecha);
    return date('Y-m-d', mktime(0, 0, 0, $mon, $day + $dia, $year));
}

function datos_plani($planilla, $tabla) {
    $sql_rep = "SELECT c.cod_cliente, c.nombre as nom_cli, g.orden, o.producto, g.guia, g.destinatario, g.direccion,
					 g.ciudad, o.peso, o.valor, g.telefono, g.id_estado, m.nombre, m.id_mensajero, m.id_sucursal
			from $tabla as g 
				 inner join mensajeros as m on (g.id_mensajero=m.id_mensajero)
				 inner join ordenes as o on (g.orden=o.orden)
				 inner join clientes as c on(g.id_cliente=c.id_cliente)
			where g.id_planilla='" . $planilla . "'";

    $rs_val = mysql_query($sql_rep, $GLOBALS["v_mysql"]);

    while ($row_rep = mysql_fetch_array($rs_val)) {
        $dato['CLIENTE'] = $row_rep['nom_cli'];
        $dato['ORDEN'] = $row_rep['orden'];
        $dato['PRODUCTO'] = $row_rep['producto'];
        $dato['GUIA'] = $row_rep['guia'];
        $dato['DESTINATARIO'] = $row_rep['destinatario'];
        $dato['DIRECCION'] = $row_rep['direccion'];
        $dato['CIUDAD'] = $row_rep['ciudad'];
        $dato['PESO'] = $row_rep['peso'];
        $dato['VALOR'] = $row_rep['valor'];
        $datos[] = $dato;
    }
    print mysql_error();
    return $datos;
}

function asignar_menu_usuario($id, $asig, $tb) {
    $coni = 0;
    foreach ($asig as $z) {
        $validar_u = "SELECT * FROM " . $tb . " WHERE id_usuario='" . $id . "' AND id_menu='" . $z . "'";
        $rs_val = mysql_query($validar_u, $GLOBALS["v_mysql"]);
        $nr = mysql_num_rows($rs_val);
        if ($nr == 0) {
            $sql_in = "INSERT INTO menu_usuario VALUES ('" . $id . "','" . $z . "')";
            $rs_val = mysql_query($sql_in, $GLOBALS["v_mysql"]);
            $affected_asignar = mysql_affected_rows();
            if ($affected_asignar >= 1) {
                $coni++;
            }
        }
    }
    if ($coni != 0) {
        $msgBOX2 = "Se Asigno Menu a Usuario.";
        echo "<script>
	             	alert('$msgBOX2');
	  		  	    </script>";
    }
}

function del_menu_usuario($id, $del, $tb) {
    $cond = 0;
    foreach ($del as $z) {
        $validar_d = "SELECT * FROM " . $tb . " WHERE id_usuario='" . $id . "' AND id_menu='" . $z . "'";
        $rs_val_d = mysql_query($validar_d, $GLOBALS["v_mysql"]);
        $nr = mysql_num_rows($rs_val_d);
        if ($nr > 0) {
            $sql_in_d = "delete from menu_usuario WHERE id_usuario='" . $id . "' AND id_menu='" . $z . "'";
            $rs_val_d = mysql_query($sql_in_d, $GLOBALS["v_mysql"]);
            $affected_del = mysql_affected_rows();
            if ($affected_del = 1) {
                $cond++;
            }
        }
    }
    if ($cond != 0) {
        $msgBOX2 = "Se Quito Menu a Usuario.";
        echo "<script>
	             	alert('$msgBOX2');
	  		  	    </script>";
    }
}

function delete($del, $tb, $wh1) {
    $cond = 0;
    $confirm = 0;
    foreach ($del as $z) {
        $validar_d = "SELECT * FROM " . $tb . " WHERE  " . $wh1 . "=" . $z . " ";
        $rs_val_d = mysql_query($validar_d, $GLOBALS["v_mysql"]);
        $nr = mysql_num_rows($rs_val_d);
        if ($nr > 0) {
            if ($tb == 'sucursales') {
                $confirm = borra_suc($z);
                $ti = 'La Sucursal';
                $nom = trim(mysql_result($rs_val_d, 0, 'nombre'));
            }
            if ($tb == 'ordenes') {
                $confirm = borra_ord($z);
                $ti = 'La Orden';
                $nom = trim(mysql_result($rs_val_d, 0, 'orden'));
            }

            if ($confirm == 0) {
                $sql_in_d = "delete from " . $tb . " WHERE " . $wh1 . "=" . $z . " ";
                $rs_val_d = mysql_query($sql_in_d, $GLOBALS["v_mysql"]);
                $affected_del = mysql_affected_rows();
                if ($affected_del = 1) {
                    $cond++;
                }
            } else {
                $msgBOX2 = "No Se Pudo Eliminar $ti $nom ya que esta siendo utilizada por otros procesos.";
                echo "<script>
						  alert('$msgBOX2');
						  window.close();
						  </script>";
            }
        }
    }
    if ($cond != 0) {
        $msgBOX2 = "Se Elimino el Resgistro Exitosamente.";
        echo "<script>
	             	alert('$msgBOX2');
	  		  	    </script>";
    } else {
        if (empty($msgBOX2)) {
            $msgBOX2 = "No Se Elimino el Resgistro.";
            echo "<script>
	           	alert('$msgBOX2');
	  	  	    </script>";
        }
    }
}

function delete_ord($del) {
    $cond = 0;
    $confirm = 0;
    foreach ($del as $z) {
        $confirm = borra_ord($z);
        $ti = 'La Orden';
        if ($confirm == 0) {
            $validar_d = "select * from ordenes where orden=" . $z . " ";
            $rs_val_d = mysql_query($validar_d, $GLOBALS["v_mysql"]);
            $nr = mysql_num_rows($rs_val_d);
            $id_suc = mysql_result($rs_val_d, 0, 'id_sucursal');
            if ($nr > 0) {
                $conf_suc = "SELECT nom_tabla, nom_rastreo FROM tablas_sucursales WHERE id_suc=" . $id_suc . " ";
                $rs_conf = mysql_query($conf_suc, $GLOBALS["v_mysql"]);
                $nom_table = mysql_result($rs_conf, 0, 'nom_tabla');
                $nom_rastreo = mysql_result($rs_conf, 0, 'nom_rastreo');

                $sql_tb = "DELETE FROM " . $nom_table . " WHERE orden = '" . $z . "' ";
                $rs_tb = mysql_query($sql_tb, $GLOBALS["v_mysql"]);

                $sql_tr = "DELETE FROM " . $nom_rastreo . " WHERE orden = '" . $z . "' ";
                $rs_tr = mysql_query($sql_tr, $GLOBALS["v_mysql"]);

                $affected_del = mysql_affected_rows();
                if ($affected_del = 1) {
                    $cond++;
                }
            }
        } else {
            $msgBOX2 = "No se puede eliminar la orden";
            echo "<script>
					alert('$msgBOX2');
					</script>";
        }
    }
}

function delete_tabla_suc($del, $tab, $wh1) {
    foreach ($del as $z) {
        $validar_d = "SELECT id_suc FROM " . $tab . " WHERE  " . $wh1 . "=" . $z . " ";
        $rs_val_d = mysql_query($validar_d, $GLOBALS["v_mysql"]);
        $nr = mysql_num_rows($rs_val_d);
        //echo $nr; echo "<br>";
        if ($nr > 0) {
            $sql_in_d = "delete from tablas_sucursales WHERE id_suc=" . $z . " ";
            //echo $sql_in_d;
            //echo "<br>";
            $rs_val_d = mysql_query($sql_in_d, $GLOBALS["v_mysql"]);
        }
    }
}

function delete_user_menu($del, $tab, $wh1, $tipo) {
    $cond = 0;
    $confirm = 0;
    foreach ($del as $z) {
        $validar_d = "SELECT id_usuario FROM " . $tab . " WHERE  " . $wh1 . "=" . $z . " ";
        $rs_val_d = mysql_query($validar_d, $GLOBALS["v_mysql"]);
        $nr = mysql_num_rows($rs_val_d);
        if ($nr > 0) {
            $user = mysql_result($rs_val_d, 0, 'id_usuario');
            if ($tb == 'sucursales')
                $confirm = borra_suc($z);
            if ($tb == 'ordenes')
                $confirm = borra_ord($z);
            if ($confirm == 0) {
                if ($tipo == 1) {
                    $sql_in_d = "delete from usuarios WHERE id_sucursal=" . $z . " ";
                    $rs_val_d = mysql_query($sql_in_d, $GLOBALS["v_mysql"]);
                }
                $sql_um = "delete from menu_usuario WHERE id_usuario=" . $user . " ";
                $rs_um = mysql_query($sql_um, $GLOBALS["v_mysql"]);
                $affected_del = mysql_affected_rows();
                if ($affected_del = 1) {
                    $cond++;
                }
            } else {
                $msgBOX2 = "No Se Pudo Eliminar Sucursal ya que esta siendo utilizada por otros procesos.";
            }
        }
    }
}

function borra_suc($id) {

    $sql_conf = "SELECT sum(cu.coun_men) as coun_men, sum(cu.coun_clie) as coun_clie, sum(cu.coun_orden) as coun_orden,
			sum(cu.coun_pla) as coun_pla
			FROM(
				select count(id_mensajero) as coun_men, 0 as coun_clie, 0 as coun_orden, 0 as coun_pla
				from sucursales as s
				inner join mensajeros as m on (m.id_sucursal=s.id_sucursal)
				where s.id_sucursal=$id
				union
				select 0 as coun_men, count(id_cliente) as coun_clie,  0 as coun_orden, 0 as coun_pla
				from sucursales as s
				inner join clientes as cl on(cl.id_sucursal=s.id_sucursal)
				where s.id_sucursal=$id
				union
				select 0 as coun_men, 0 as coun_clie, count(id_orden) as coun_orden,   0 as coun_pla
				from sucursales as s
				inner join ordenes as o on(o.id_sucursal=s.id_sucursal)
				where s.id_sucursal=$id
				union
				select 0 as coun_men, 0 as coun_clie, 0 as coun_orden, count(id_planilla) as coun_pla
				from sucursales as s
				inner join planillas as p on(p.id_sucursal=s.id_sucursal)
				where s.id_sucursal=$id
			) cu";
    //echo $sql_conf;
    //echo "<br>";
    $rs_conf = mysql_query($sql_conf, $GLOBALS["v_mysql"]);
    $coun_men = mysql_result($rs_conf, 0, 'coun_men');
    $coun_clie = mysql_result($rs_conf, 0, 'coun_clie');
    $coun_orden = mysql_result($rs_conf, 0, 'coun_orden');
    $coun_pla = mysql_result($rs_conf, 0, 'coun_pla');
    if ($coun_men != 0 or $coun_clie != 0 or $coun_orden != 0 or $coun_pla != 0) {
        $confir = 1;
    } else {
        $confir = 0;
    }
    return $confir;
}

function borra_ord($orden) {
    $val_fec = "select o.id_orden, o.orden, o.fecha_creacion, c.id_cliente, c.nombre, c.tiempo_vencimiento, count(g.guia),
if(o.fecha_creacion>=DATE_ADD(o.fecha_creacion, INTERVAL COALESCE(c.tiempo_vencimiento,0) MONTH) or count(g.guia)=0 ,'S','N') as fecha_ven
from ordenes as o
left outer join guias_proceso as g on (o.orden=g.orden)
inner join clientes as c on (o.id_cliente=c.id_cliente) 
			where o.orden=" . $orden . " group by o.orden";
    echo $val_fec;
    $rs_fec = mysql_query($val_fec, $GLOBALS["v_mysql"]);
    $borra = mysql_result($rs_fec, 0, 'fecha_ven');
    if ($borrar == 'S') {
        $confir = 0;
    } else {
        $confir = 1;
    }
    return $confir;
}

function update_zonas($codigo, $cod_suc, $valor_entrega, $valor_devolucion) {
    $cond = 0;
    $i = 0;
    foreach ($codigo as $z) {
        $i++;
        $sql_mod = "update zonificacion_cs set id_sucursal=" . $cod_suc[$i] . ", valor_entrega=" . $valor_entrega[$i] . ",
			           valor_devolucion=" . $valor_devolucion[$i] . " where codigo=" . $z . " ";
        //echo $sql_mod;
        //echo "<br>";
        $rs_mod = mysql_query($sql_mod, $GLOBALS["v_mysql"]);
        $affected_mod = mysql_affected_rows();
        if ($affected_mod = 1) {
            $cond++;
        }
    }
    if ($cond != 0) {
        $msgBOX2 = "Se Actualizaron el Resgistro Exitosamente.";
        echo "<script>
	             	alert('$msgBOX2');
	  		  	    </script>";
    }
}

function con_max($tabla, $cam) {
    $sql_con = "select max($cam) as con from $tabla";
    $rs_con = mysql_query($sql_con, $GLOBALS["v_mysql"]);
    $nm = mysql_result($rs_con, 0, 'con');
    return $nm = $nm + 1;
}

function escoger_suc($cod_suc) {
    $sql_su = "select id_sucursal from sucursales where cod_sucursal=$cod_suc";
    $res = mysql_query($sql_su, $GLOBALS["v_mysql"]);
    $id_s = mysql_result($res, 0, 'id_sucursal');
    return $id_s;
}

function escoger_usuario($user) {
    $sql_us = "select id_usuario from usuarios where usuario='$user' ";
    $res = mysql_query($sql_us, $GLOBALS["v_mysql"]);
    $id_us = mysql_result($res, 0, 'id_usuario');
    return $id_us;
}

function escoger_menus() {
    $sql_men = "select id from menu ";
    $res = mysql_query($sql_men, $GLOBALS["v_mysql"]);
    $i = 0;
    while ($row = mysql_fetch_array($res)) {
        $i++;
        $asig_m[$i] = $row['id'];
    }
    return $asig_m;
}

function get_field($tabla_1) {
    $sql = "SHOW COLUMNS FROM $tabla_1";
    $resultado = mysql_query($sql, $GLOBALS["v_mysql"]);
    $j = 0;
    while ($row = mysql_fetch_array($resultado)) {
        $campo_temp[] = $row['Field'];
        echo"<option value=" . $row['Field'] . ">" . $row['Field'] . "</option>";
        $j++;
    }
    return $campo_temp;
}

function get_usuario() {
    $sql = "SELECT id_usuario, nombre FROM usuarios";
    $resultado = mysql_query($sql, $GLOBALS["v_mysql"]);
    $j = 0;
    while ($row = mysql_fetch_array($resultado)) {
        echo"<option value=" . $row['id'] . ">" . $row['nombre'] . "</option>";
        $j++;
    }
    return $campo_temp;
}

function get_sucursal($perfil, $id_sucursal) {
    print "<select name='sucursal' id='sucursal' class='inputbox' style='width:260px'>";
    if ($perfil == 1) {
        $sql = "SELECT id_sucursal, nombre FROM sucursales";
        echo "<option value=''>Seleccion una Sucursal</option>";
    } else {
        $sql = "SELECT id_sucursal, nombre FROM sucursales where id_sucursal=$id_sucursal ";
    }
    $resultado = mysql_query($sql, $GLOBALS["v_mysql"]);
    $j = 0;
    while ($row = mysql_fetch_array($resultado)) {
        echo"<option value=" . $row['id_sucursal'] . ">" . $row['nombre'] . "</option>";
        $j++;
    }
    print"</select>";
    //return $campo_temp;
}

function get_depto() {
    $sql = "SELECT cod_depto, nombre FROM departamentos order by nombre";
    $resultado = mysql_query($sql, $GLOBALS["v_mysql"]);
    $j = 0;
    while ($row = mysql_fetch_array($resultado)) {
        echo"<option value=" . $row['cod_depto'] . ">" . $row['nombre'] . "</option>";
        $j++;
    }
    return $campo_temp;
}

function get_ciudad() {
    $sql_ciudad = "SELECT id_ciudad, nombre FROM ciudades order by nombre";
    $rst_get_ciudad = mysql_query($sql_ciudad, $GLOBALS["v_mysql"]);
    while ($row_get_ciudad = mysql_fetch_array($rst_get_ciudad)) {

        if (trim($row_get_ciudad['id_ciudad']) == '1061') {
            $selected = ' selected="selected"';
        } else {
            $selected = '';
        }
        echo"<option " . "$selected value=" . $row_get_ciudad['id_ciudad'] . ">" . $row_get_ciudad['nombre'] . "</option>";
    }
}

function get_departamentos() {
    $sql_dpto = "SELECT cod_depto,nombre FROM departamentos order by nombre";
    $rst_get_dpto = mysql_query($sql_dpto, $GLOBALS["v_mysql"]);
    while ($row_get_dpto = mysql_fetch_array($rst_get_dpto)) {
        echo"<option value=" . $row_get_dpto['cod_depto'] . " .$selected>" . $row_get_dpto['nombre'] . "</option>";
    }
}

function get_cliente($suc) {
    $perfil = $_SESSION['perfil'];
    if ($perfil == 1) {
        $sql_cliente = "SELECT id_cliente, nombre FROM clientes";
    } else {
        $sql_cliente = "SELECT id_cliente, nombre FROM clientes WHERE id_sucursal = '$suc'";
    }
    $rst_get_ciudad = mysql_query($sql_cliente, $GLOBALS["v_mysql"]);
    while ($row_get_ciudad = mysql_fetch_array($rst_get_ciudad)) {
        echo"<option value=" . $row_get_ciudad['id_cliente'] . ">" . $row_get_ciudad['nombre'] . "</option>";
    }
}

function get_sucursales($suc, $id_suc) {
    $perfil = $_SESSION['perfil'];
    if ($perfil == 1) {
        $sql_suc = "SELECT id_sucursal, nombre FROM sucursales";
    } else {
        $sql_suc = "SELECT id_sucursal, nombre FROM sucursales WHERE id_sucursal = '$suc' ";
    }
    $rst_get_sucursal = mysql_query($sql_suc, $GLOBALS["v_mysql"]);
    while ($row_get_sucursal = mysql_fetch_array($rst_get_sucursal)) {
        if ($id_suc == $row_get_sucursal[0]) {
            $selected = 'selected';
        } else {
            $selected = '';
        }
        echo"<option value=" . $row_get_sucursal[0] . " " . $selected . ">" . $row_get_sucursal[1] . "</option>";
    }
}

function get_sucursales_todas($suc, $id_suc) {
    $perfil = $_SESSION['perfil'];
    $sql_suc = "SELECT id_sucursal, nombre FROM sucursales";
    $rst_get_sucursal = mysql_query($sql_suc, $GLOBALS["v_mysql"]);
    while ($row_get_sucursal = mysql_fetch_array($rst_get_sucursal)) {
        if ($id_suc == $row_get_sucursal[0]) {
            $selected = 'selected';
        } else {
            $selected = '';
        }
        echo"<option value=" . $row_get_sucursal[0] . " " . $selected . ">" . $row_get_sucursal[1] . "</option>";
    }
}

function get_mensajero($suc, $id_mens) {
    $perfil = $_SESSION['perfil'];
$area='';
if($_SESSION['area']!='0'){
	$area=' and area   in ('.$_SESSION['area'].') ';
}
$zona='';
/*if($_SESSION['zona']!=0){
    $zona=' and zona="'.$_SESSION['zona'].'" ';
}*/
    if ($perfil == 1) {
        $sql_mens = "SELECT id_mensajero, nombre FROM mensajeros WHERE estado = '1' ".$area.$zona." order by  nombre";
    } else {
        $sql_mens = "SELECT id_mensajero, nombre FROM mensajeros WHERE id_sucursal = '$suc' 
        AND estado = '1' ".$area.$zona." order by  nombre";
    }
    
    $rst_get_mensajero = mysql_query($sql_mens, $GLOBALS["v_mysql"]);
    while ($row_get_mensajero = mysql_fetch_array($rst_get_mensajero)) {
        if ($id_mens == $row_get_mensajero[0]) {
            $selected = 'selected';
        } else {
            $selected = '';
        }
        echo"<option value=" . $row_get_mensajero[0] . " " . $selected . ">" . $row_get_mensajero[1] . "</option>";
    }
}

function get_mensajero2($suc, $id_mens) {
    $perfil = $_SESSION['perfil'];
    if ($perfil == 1) {
        $sql_mens = "SELECT id_mensajero, nombre FROM mensajeros WHERE estado = '1' order by  nombre";
    } else {
        $sql_mens = "SELECT id_mensajero, nombre FROM mensajeros WHERE id_sucursal = '$suc' AND estado = '1' order by  nombre";
    }
    $rst_get_mensajero = mysql_query($sql_mens, $GLOBALS["v_mysql"]);
    echo '<select name="id_mens" id="id_mens" class="inputbox" style="width:300px">
        	        <option value=""> </option>';
    while ($mensa = mysql_fetch_array($rst_get_mensajero)) {
        echo "<option value='$mensa[0]' ";
        if ($id_mens == $mensa[0])
            echo "selected='selected'";
        echo ">$mensa[1]</option>";
    }
    echo '</select>';
}

function get_motivo($suc, $motivo) {
    $sql_motivo = "SELECT id_devolucion, nombre FROM devoluciones";
    $rst_get_movito = mysql_query($sql_motivo, $GLOBALS["v_mysql"]);
    while ($row_get_motivo = mysql_fetch_array($rst_get_movito)) {
        if ($motivo == $row_get_motivo[0]) {
            $selected = 'selected';
        } else {
            $selected = '';
        }
        echo"<option value=" . $row_get_motivo[0] . " " . $selected . ">" . $row_get_motivo[1] . "</option>";
    }
}

function get_zonau($suc, $motivo) {
    $sql_zonau = "SELECT codigo, nombre FROM zonificacion_cs";
    $rst_get_zonau = mysql_query($sql_zonau, $GLOBALS["v_mysql"]);
    while ($row_get_zonau = mysql_fetch_array($rst_get_zonau)) {
        if ($motivo == $row_get_zonau[0]) {
            $selected = 'selected';
        } else {
            $selected = '';
        }
        echo"<option value=" . $row_get_zonau[0] . " " . $selected . ">" . $row_get_zonau[1] . "</option>";
    }
}

function get_zonan() {
    $sql = "SELECT id_zona_nal, nombre FROM zonas_nacionales where id_zona_nal>='1'";
    $resultado = mysql_query($sql, $GLOBALS["v_mysql"]);
    $j = 0;
    while ($row = mysql_fetch_array($resultado)) {
        echo"<option value=" . $row['id_zona_nal'] . ">" . $row['nombre'] . "</option>";
        $j++;
    }
    return $campo_temp;
}

function entrada($user, $id_user, $id_suc) {
    $sql_mens = "SELECT * FROM usuarios WHERE usuario='" . $user . "' AND id_usuario='" . $id_user . "' AND id_sucursal='" . $id_suc . "'";
    $rst_get_entrada = mysql_query($sql_mens, $GLOBALS["v_mysql"]);
    $cant = mysql_num_rows($rst_get_entrada);
    if ($cant <= 0) {
        $msgBOX = "Se Ha Detectado Un Error en el Sistema.";
        ?>
        <script>
            setTimeout("location.href='index.php'", 100);
            alert('<?php echo $msgBOX; ?>');
        </script>
                <?
            }
        }

        class select_zonas {

            var $conexionObj2;

            function entrada2($user, $id_user, $id_suc) {
                $this->conexionObj2 = new conexion();
                $this->conexionObj2->conectarse();
                $rst_ingreso = $this->conexionObj2->consultar("SELECT * FROM usuarios WHERE usuario='" . $user . "' AND id_usuario='" . $id_user . "' AND id_sucursal='" . $id_suc . "'");
                if (mysql_num_rows($rst_ingreso) <= 0) {
                    $msgBOX = "Se Ha Detectado Un Error en el Sistema.";
                    ?>
            <script>
            //setTimeout("location.href='index.php'", 100);
                alert('<?php echo $msgBOX; ?>');
            </script>
            <?
        }
    }

    function get_filas($sql_consulta) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $rst_ingreso = $this->conexionObj2->consultar("$sql_consulta");
        $cant = mysql_num_rows($rst_ingreso);
        return $cant;
    }

    function get_array($sql_consulta) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $rst_ingreso = $this->conexionObj2->consultar("$sql_consulta");
        while ($array = mysql_fetch_array($rst_ingreso)) {
            $nuevo_array[] = $array;
        }
        return $nuevo_array;
    }

    function zonas_sucursal($id_suc) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $rst_suc = $this->conexionObj2->consultar("SELECT id_sucursal, nombre FROM sucursales order by id_sucursal");
        while ($row_suc = mysql_fetch_array($rst_suc)) {
            ?>
            <option value="<?= $row_suc[0] ?>" <?
                    if ($id_suc == $row_suc[0]) {
                        echo 'selected';
                    }
                    ?>><?= $row_suc[1] ?></option>
            <?
        }
    }

    function zonas_nacionales($zona) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        echo "SELECT id_zona_nal, nombre FROM zonas_nacionales WHERE id_zona_nal >='1'";
        $rst_select_lotes = $this->conexionObj2->consultar("SELECT id_zona_nal, nombre FROM zonas_nacionales WHERE id_zona_nal >='1'");
        echo "<option value='0'>Sin Zona Nacional</option>";
        while ($row_zonas = mysql_fetch_array($rst_select_lotes)) {
            ?><option value="<?= $row_zonas['id_zona_nal'] ?>" <?
            if ($zona == $row_zonas['id_zona_nal']) {
                echo 'selected';
            }
            ?>><?= $row_zonas['nombre'] ?></option><?
        }
    }

    function zonas_nac($inicio, $tamano_pagina, $add) {
        $i = 0;
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $rst_select_lotes = $this->conexionObj2->consultar("SELECT * FROM zonas_nacionales $add order by id_zona_nal LIMIT $inicio,$tamano_pagina");
        while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
            $i++;
            echo "<tr class=miTable_tr>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['id_zona_nal'] . "</td>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['nombre'] . "</td>";
            echo "<td valign=middle class=miTable_td>";
            ?>
            <a href='accion_zonas_n.php?id_zona=<? echo "" . $row_select_lotes['id_zona_nal'] . ""; ?>&tipo=1' onClick="window.open('accion_zonas_n.php?id_zona=<? echo "" . $row_select_lotes['id_zona_nal'] . ""; ?>&tipo=1&nombre=<? echo "" . $row_select_lotes['nombre'] . ""; ?>', 'window', 'width=300,height=200');
                    return false">
                <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td>
                <a href='accion_zonas_n.php?id_zona=<? echo "" . $row_select_lotes['id_zona_nal'] . ""; ?>&tipo=2' onClick="window.open('accion_zonas_n.php?id_zona=<? echo "" . $row_select_lotes['id_zona_nal'] . ""; ?>&tipo=2&nombre=<? echo "" . $row_select_lotes['nombre'] . ""; ?>', 'window', 'width=300,height=200');
                    return false">
                    <img src='imagenes/del.gif'></a><?
            echo "<input type=checkbox id='del_zn' name='del_zn[$i]' value=" . $row_select_lotes['id_zona_nal'] . " class=inputbox ></td>";
        }
    }

    function option_ciudad($cod_ciudad) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $rst_ciu = $this->conexionObj2->consultar("SELECT id_ciudad, nombre FROM ciudades order by id_ciudad, nombre");
        while ($row_ciu = mysql_fetch_array($rst_ciu)) {
            ?>
            <option value="<?= $row_ciu['id_ciudad'] ?>" <?
            if ($cod_ciudad == $row_ciu['id_ciudad']) {
                echo 'selected';
            }
            ?>><?= $row_ciu['nombre'] ?></option>
                <?
            }
        }

        function option_dpto($cod_depto) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $rst_dpto = $this->conexionObj2->consultar("SELECT id_depto, nombre, cod_depto FROM departamentos order by  nombre");
            while ($row_dpto = mysql_fetch_array($rst_dpto)) {
                ?>
            <option value="<?= $row_dpto['id_depto'] ?>" <?
                if ($cod_depto == $row_dpto['id_depto']) {
                    echo 'selected';
                }
                ?>><?= $row_dpto['nombre'] ?></option>
                <?
            }
        }

        function lista_estados($inicio, $tamano_pagina, $add) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT * FROM estados_gestion $add order by cod_estado LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['1'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['2'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['3'] . "</td>";
                echo "<td valign=middle class=miTable_td>";
                ?>
            <a href='accion_estados.php?id=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=1' onClick="window.open('accion_estados.php?id=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=1&codigo=<? echo "" . $row_select_lotes['1'] . ""; ?>&nombre=<? echo "" . $row_select_lotes['2'] . ""; ?>&descripcion=<? echo "" . $row_select_lotes['3'] . ""; ?>', 'window', 'width=350,height=300');
                    return false">
                <center><img src='imagenes/reload_.gif'></center></a>
            </td>
                <?
            }
        }

        function get_sucursales2($suc) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $perfil = $_SESSION['perfil'];
            if ($perfil == 1) {
                $add = '';
            } else {
                $add = "WHERE id_sucursal = '$suc'";
            }
            $rst_ciu = $this->conexionObj2->consultar("SELECT id_sucursal, nombre FROM sucursales $add order by id_sucursal");
            while ($row_ciu = mysql_fetch_array($rst_ciu)) {
                ?><option value="<?= $row_ciu[0] ?>" <?
                if ($suc == $row_ciu[0]) {
                    echo 'selected';
                }
                ?>><?= $row_ciu['nombre'] ?></option>
                <?
            }
        }

        function toma_sucursal($suc) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $perfil = $_SESSION['perfil'];
            if ($perfil == 1) {
                $rst_ciu = $this->conexionObj2->consultar("SELECT id_sucursal, nombre FROM sucursales order by id_sucursal");
            } else {
                $rst_ciu = $this->conexionObj2->consultar("SELECT id_sucursal, nombre FROM sucursales  order by id_sucursal");
            }
            while ($row_ciu = mysql_fetch_array($rst_ciu)) {
                ?>
            <option value="<?= $row_ciu[0] ?>" <? if ($suc == $row_ciu[0]) {
                echo 'selected';
            } ?>><?= $row_ciu[1] ?></option>
                <?
            }
        }

        function lista_dev($inicio, $tamano_pagina, $add) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT * FROM devoluciones $add order by id_devolucion LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['1'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['2'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['3'] . "</td>";
                echo "<td valign=middle class=miTable_td>";
                ?>
            <a href='accion_devolucion.php?id=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=1' onClick="window.open('accion_devolucion.php?id=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=1&codigo=<? echo "" . $row_select_lotes['1'] . ""; ?>&nombre=<? echo "" . $row_select_lotes['2'] . ""; ?>&desc=<? echo "" . $row_select_lotes['3'] . ""; ?>', 'window', 'width=350,height=300');
                    return false">
                <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td width="50">
                <a href='accion_devolucion.php?id=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=2' onClick="window.open('accion_devolucion.php?id=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=2&codigo=<? echo "" . $row_select_lotes['1'] . ""; ?>&nombre=<? echo "" . $row_select_lotes['2'] . ""; ?>&desc=<? echo "" . $row_select_lotes['3'] . ""; ?>', 'window', 'width=350,height=300');
                    return false"><img src='imagenes/del.gif'></a>
                <?
                echo "<input type=checkbox id='del_dev' name='del_dev[$i]' value=" . $row_select_lotes['0'] . " class=inputbox ></td>";
            }
        }

        function zonas_urb($inicio, $tamano_pagina, $add) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $id_suc = $_GET['suc'];
            $perfil = $_SESSION['perfil'];
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT cod_zona,nom_zona FROM zonas_urbanas $add order by cod_zona LIMIT $inicio,$tamano_pagina");
            $i = 0;
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                $i++;
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['cod_zona'] . "<input type='hidden' id='codigo' name='codigo[$i]'  value='" . $row_select_lotes['cod_zona'] . "' size='8'></td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['nom_zona'] . "</td>";

                echo "<td valign=middle class=miTable_td>";
                ?>
                <a href='accion_zonas_u.php?codigo=<? echo "" . $row_select_lotes['cod_zona'] . ""; ?>&tipo=1' onClick="window.open('accion_zonas_u.php?codigo=<? echo "" . $row_select_lotes['cod_zona'] . ""; ?>&tipo=1&nombre=<? echo "" . $row_select_lotes['nom_zona'] . ""; ?>', 'window', 'width=350,height=300');
                    return false">
                    <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td width="50">
                <a href='accion_zonas_u.php?codigo=<? echo "" . $row_select_lotes['cod_zona'] . ""; ?>&tipo=2' onClick="window.open('accion_zonas_u.php?codigo=<? echo "" . $row_select_lotes['cod_zona'] . ""; ?>&tipo=2&nombre=<? echo "" . $row_select_lotes['nom_zona'] . ""; ?>', 'window', 'width=350,height=300');
                    return false">
                    <img src='imagenes/del.gif'></a><?
                echo "<input type=checkbox id='del_zn_u' name='del_zn_u[$i]' value=" . $row_select_lotes['id_zona_urb'] . " class=inputbox ></td>";
            }
        }

        function zonas_urb_2($inicio, $tamano_pagina, $add) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $id_suc = $_GET['sucursal'];
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT u.id_zona_urb, u.cod_zona, u.nom_zona, u.id_sucursal, s.nombre as nom_suc, u.valor_entrega, u.valor_devolucion  FROM zonas_urbanas as u
     inner join sucursales as s on (u.id_sucursal=s.id_sucursal) $add order by u.id_zona_urb LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['cod_zona'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['nom_zona'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['nom_suc'] . "</td>";
                echo "<td valign=top class=miTable_td>$" . $row_select_lotes['valor_entrega'] . "</td>";
                echo "<td valign=top class=miTable_td>$" . $row_select_lotes['valor_devolucion'] . "</td>";
                echo "<td valign=middle class=miTable_td>";
                ?>
                <a href='accion_zonas_u.php?id_zona=<? echo "" . $row_select_lotes['id_zona_urb'] . ""; ?>&tipo=1' onClick="window.open('accion_zonas_u.php?id_zona=<? echo "" . $row_select_lotes['id_zona_urb'] . ""; ?>&tipo=1&nombre=<? echo "" . $row_select_lotes['nom_zona'] . ""; ?>&codigo=<? echo "" . $row_select_lotes['cod_zona'] . ""; ?>&id_suc=<? echo "" . $row_select_lotes['id_sucursal'] . ""; ?>&valor=<? echo "" . $row_select_lotes['valor_entrega'] . ""; ?>&valord=<? echo "" . $row_select_lotes['valor_devolucion'] . ""; ?>', 'window', 'width=350,height=300');
                    return false">
                    <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td width="50">
                <a href='accion_zonas_u.php?id_zona=<? echo "" . $row_select_lotes['id_zona_urb'] . ""; ?>&tipo=2' onClick="window.open('accion_zonas_u.php?id_zona=<? echo "" . $row_select_lotes['id_zona_urb'] . ""; ?>&tipo=2&nombre=<? echo "" . $row_select_lotes['nom_zona'] . ""; ?>&codigo=<? echo "" . $row_select_lotes['cod_zona'] . ""; ?>&id_suc=<? echo "" . $row_select_lotes['id_sucursal'] . ""; ?>&valor=<? echo "" . $row_select_lotes['valor_entrega'] . ""; ?>&valord=<? echo "" . $row_select_lotes['valor_devolucion'] . ""; ?>', 'window', 'width=350,height=300');
                    return false">
                    <img src='imagenes/del.gif'></a><?
                    echo "<input type=checkbox id='del_zn_u' name='del_zn_u[$i]' value=" . $row_select_lotes['id_zona_urb'] . " class=inputbox ></td>";
                }
            }

            function lista_sucursal($inicio, $tamano_pagina, $add) {
                $this->conexionObj2 = new conexion();
                $this->conexionObj2->conectarse();
                if (!empty($add)) {
                    $add2 = " and s.id_ciudad=c.id_ciudad";
                } else {
                    $add2 = "where s.id_ciudad=c.id_ciudad";
                }
                $rst_select_lotes = $this->conexionObj2->consultar("SELECT s.id_sucursal, s.cod_sucursal, s.nombre, s.nit, s.direccion, s.telefono, s.contacto, s.mail, s.id_ciudad, c.nombre as nom_ciu FROM sucursales as s, ciudades as c  $add  $add2 order by id_sucursal LIMIT $inicio,$tamano_pagina");
                //$rst_select_lotes2="SELECT s.cod_sucursal, s.nombre, s.nit, s.direccion, s.telefono, s.contacto, s.mail, s.id_ciudad, c.nombre as nom_ciu FROM sucursales as s, ciudades as c  $add  $add2 order by id_sucursal LIMIT $inicio,$tamano_pagina";
                //echo $rst_select_lotes2;
                while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                    echo "<tr class=miTable_tr>";
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes['cod_sucursal'] . "</td>";
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes['nombre'] . "</td>";
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes['nit'] . "</td>";
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes['direccion'] . "</td>";
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes['telefono'] . "</td>";
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes['nom_ciu'] . "</td>";
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes['contacto'] . "</td>";
                    echo "<td valign=middle class=miTable_td width='50' >";
                    ?>
                <a href='accion_sucursal.php?id=<? echo "" . $row_select_lotes['id_sucursal'] . ""; ?>&tipo=1' onClick="window.open('accion_sucursal.php?id=<? echo "" . $row_select_lotes['id_sucursal'] . ""; ?>&tipo=1&nombre=<? echo "" . $row_select_lotes['nombre'] . ""; ?>&nit=<? echo "" . $row_select_lotes['nit'] . ""; ?>&telefono=<? echo "" . $row_select_lotes['telefono'] . ""; ?>&direccion=<? echo "" . $row_select_lotes['direccion'] . ""; ?>&email=<? echo "" . $row_select_lotes['mail'] . ""; ?>&rep=<? echo "" . $row_select_lotes['contacto'] . ""; ?>&cod_ciudad=<? echo "" . $row_select_lotes['id_ciudad'] . ""; ?>', 'window', 'width=350,height=300');
                    return false">
                    <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td width='60'>
                <? if ($row_select_lotes['id_sucursal'] != 1) { ?>
                    <a href='accion_sucursal.php?id=<? echo "" . $row_select_lotes['id_sucursal'] . ""; ?>&tipo=2' onClick="window.open('accion_sucursal.php?id=<? echo "" . $row_select_lotes['id_sucursal'] . ""; ?>&tipo=2&nombre=<? echo "" . $row_select_lotes['nombre'] . ""; ?>&nit=<? echo "" . $row_select_lotes['nit'] . ""; ?>&telefono=<? echo "" . $row_select_lotes['telefono'] . ""; ?>&direccion=<? echo "" . $row_select_lotes['direccion'] . ""; ?>&email=<? echo "" . $row_select_lotes['mail'] . ""; ?>&rep=<? echo "" . $row_select_lotes['contacto'] . ""; ?>&cod_ciudad=<? echo "" . $row_select_lotes['id_ciudad'] . ""; ?>', 'window', 'width=350,height=300');
                        return false">
                        <img src='imagenes/del.gif'></a>
                    <?
                    print"<input type=checkbox id='del_suc' name='del_suc[$i]' value=" . $row_select_lotes['id_sucursal'] . " class=inputbox ></td>";
                }//termina el ir de sucursal 1
            }
        }

        function lista_mensajero($inicio, $tamano_pagina, $suc, $perfil, $add) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT u.id_mensajero, u.nombre, u.identificacion, u.direccion, u.telefono, u.movil, u.id_sucursal, s.nombre as nom_suc, u.observaciones, u.estado, u.id_ciudad  FROM mensajeros as u
     inner join sucursales as s on (u.id_sucursal=s.id_sucursal) $add order by u.id_mensajero LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[4] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[5] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[7] . "</td>";
                echo "<td valign=middle class=miTable_td>";
                ?>
                <a href='accion_mensajero.php?id=<? echo "" . $row_select_lotes[0] . ""; ?>&tipo=1' onClick="window.open('accion_mensajero.php?id=<? echo "" . $row_select_lotes[0] . ""; ?>&tipo=1', 'window', 'width=300,height=360');
                    return false">
                    <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td width="60">
                <a href='accion_mensajero.php?id=<? echo "" . $row_select_lotes[0] . ""; ?>&tipo=2' onClick="window.open('accion_mensajero.php?id=<? echo "" . $row_select_lotes[0] . ""; ?>&tipo=2', 'window', 'width=300,height=360');
                    return false"><img src='imagenes/del.gif'></a>
                <?
                echo "<input type=checkbox id='del_men' name='del_men[$i]' value=" . $row_select_lotes[0] . " class=inputbox >";
                echo "</td>";
            }
        }

        function lista_mensajero_p($inicio, $tamano_pagina, $suc, $perfil, $f1, $f2, $tabla) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            if ($perfil == 1) {
                $add = "WHERE r.F13>='" . $f1 . "' AND r.F13<'" . $f2 . "' ";
            } else {
                $add = "WHERE m.id_sucursal='$suc' AND r.F13>='" . $f1 . "' AND r.F13<'" . $f2 . "' ";
            }
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT m.id_mensajero, m.nombre, m.identificacion, count(g.guia)
			  			FROM guias_proceso as g 
						inner join mensajeros as m on (g.id_mensajero=m.id_mensajero)
						inner join rastreo_guias as r on (g.guia=r.guia) 
						$add group by g.id_mensajero LIMIT $inicio,$tamano_pagina");


            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
                echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td>";
                ?><a href="ver_pendiente_general.php?id_user=<? echo $_GET['id_user']; ?>&suc=<? echo $_GET['suc']; ?>&id_mens=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>&nommens=<? echo $row_select_lotes[1]; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>&id_est=0"><? echo $row_select_lotes[3]; ?></a>
                <?
                echo "</td>";
                ///////////////Entregas
                $IdMsj=$row_select_lotes[0];
                $StrSql="select count(*) from guias_proceso as a inner join rastreo_guias as r on a.guia=r.guia
                        $add and a.id_mensajero='".$IdMsj."' and a.id_estado in(14,15)";
                $rst_entregas = $this->conexionObj2->consultar($StrSql);
                $row_entregas=  mysql_fetch_array($rst_entregas);
                echo "<td valign=top class=miTable_td>";
                ?><a href="ver_pendiente_general.php?id_user=<? echo $_GET['id_user']; ?>&suc=<? echo $_GET['suc']; ?>&id_mens=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>&nommens=<? echo $row_select_lotes[1]; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>&id_est=14"><? echo $row_entregas[0]; ?></a>
                <?
                echo "</td>";    
                /////////////////////Devoluciones                
                $StrSql="select count(*) from guias_proceso as a inner join rastreo_guias as r on a.guia=r.guia
                        $add and a.id_mensajero='".$IdMsj."' and a.id_estado='16'";
                $rst_devol = $this->conexionObj2->consultar($StrSql);
                $row_devol=  mysql_fetch_array($rst_devol);
                echo "<td valign=top class=miTable_td>";
                ?><a href="ver_pendiente_general.php?id_user=<? echo $_GET['id_user']; ?>&suc=<? echo $_GET['suc']; ?>&id_mens=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>&nommens=<? echo $row_select_lotes[1]; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>&id_est=16"><? echo $row_devol[0]; ?></a>
                <?
                echo "</td>";    
                /////////////////////////Pendientes                
                $StrSql="select count(*) from guias_proceso as a inner join rastreo_guias as r on a.guia=r.guia
                $add and a.id_mensajero='".$IdMsj."' and a.id_estado='13'";
                $rst_pen = $this->conexionObj2->consultar($StrSql);
                $row_pen=  mysql_fetch_array($rst_pen);
                $TotPen=$TotPen+$row_pen[0];
                echo "<td valign=top class=miTable_td>";
                ?><a href="ver_pendiente_general.php?id_user=<? echo $_GET['id_user']; ?>&suc=<? echo $_GET['suc']; ?>&id_mens=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>&nommens=<? echo $row_select_lotes[1]; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>&id_est=13"><? echo $row_pen[0]; ?></a>
                <?
                echo "</td>";
            }
        }

        function lista_ods_p($inicio, $tamano_pagina, $suc, $perfil, $orden, $tabla) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            if ($perfil == 1) {
                $add = "WHERE g.id_estado='13' AND orden = '$orden'";
            } else {
                $add = "WHERE m.id_sucursal='$suc' AND g.id_estado='13' AND orden = '$orden'";
            }
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT m.nombre, count(guia), g.id_mensajero FROM mensajeros as m " .
                    "inner join $tabla as g on m.id_mensajero=g.id_mensajero AND m.id_sucursal=g.id_sucursal $add group by  g.id_mensajero ORDER BY m.nombre LIMIT $inicio,$tamano_pagina");
            
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>";
                ?>
                <A HREF="accion_pendientes_ods.php?tabla=<? echo $tabla; ?>
                   &suc=<? echo $suc; ?>&id_mens=<? echo $row_select_lotes[2]; ?>
                   &orden=<? echo trim($orden); ?>",onClick='window.open("accion_pendientes_ods.php?tabla=<? echo $tabla; ?>
                   &suc=<? echo $suc; ?>&id_mens=<? echo $row_select_lotes[2]; ?>&orden=<? echo trim($orden); ?>",
                   "window","width=750,height=600,toolbars=no,scrollbars=yes,resizable=yes"); return false' target="_blank">Ver Pendientes</A>
            <!--					<A HREF="accion_pendientes_ods.php?tabla=<? echo $tabla; ?>&suc=<? echo $suc; ?>&id_mens=<? echo $row_select_lotes[2]; ?>&orden=<? echo trim($orden); ?>&zona=<? echo $row_select_lotes[1]; ?>", onClick='window.open("accion_pendientes_ods.php?tabla=<? echo $tabla; ?>&suc=<? echo $suc; ?>&id_mens=<? echo $row_select_lotes[3]; ?>&orden=<? echo trim($orden); ?>&zona=<? echo $row_select_lotes[1]; ?>","window","width=750,height=600,toolbars=no,scrollbars=yes,resizable=yes"); return false'>Ver Pendientes</A>-->
                <?
                echo "</td>";
            }
        }

        function nomina_mensajero($inicio, $tamano_pagina, $suc, $perfil, $f1, $f2, $tabla, $mensajero) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
// 		if($perfil==1){
// 			$add="WHERE id_mensajero = '".$mensajero."' AND fecha_cargue BETWEEN '".$f1."' AND '".$f2."'
//			  AND (g.id_estado='14' OR g.id_estado='15' OR g.id_estado='16')";
// 		}else{
// 			$add="WHERE id_mensajero = '".$mensajero."' AND fecha_cargue BETWEEN '".$f1."' AND '".$f2."'
//			  AND g.id_sucursal='".$suc."' AND (g.id_estado='14' OR g.id_estado='15' OR g.id_estado='16')";
// 		}

            $sql_nomina = "select c.nombre as estado,count(*) as cantidad,b.nombre as mensajero from guias_proceso as a
			inner join mensajeros as b on a.id_mensajero=b.id_mensajero
			inner join estados_gestion as c on a.id_estado=c.id_estado
 			where a.id_mensajero='" . $mensajero . "'
			and a.fecha_cargue>='" . $f1 . "' and a.fecha_cargue<='" . $f2 . "'
			group by a.id_estado";
            $rst_select_lotes = $this->conexionObj2->consultar($sql_nomina);





            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                //echo "<td valign=top class=miTable_td>".$row_select_lotes[2]."</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
                $sum = $sum + $row_select_lotes[3];
                $total = $row_select_lotes[3] * $row_select_lotes[1];
                $totalg = $totalg + $total;
                ?>
                   <!--a href="ver_pendiente_general.php?id_user=<? echo $_GET['id_user']; ?>&suc=<? echo $_GET['suc']; ?>&id_mens=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>&nommens=<? echo $row_select_lotes[1]; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>"><? echo $row_select_lotes[3]; ?></a-->
                <?
                echo "</tr>";
            }
            echo "<tr class=miTable_tr>
					<td class=miTable_th1 colspan='3'>Cantidad de Guias</td>
                    <td class=miTable_th1>" . $sum . "</td>
					</tr>
					<tr class=miTable_tr>
					<td class=miTable_th1 colspan='3'>Total a Pagar</td>
					<td class=miTable_th1>$" . number_format($totalg, 2, ',', '.') . "</td>
					</tr>";
        }

        function nomina_general($inicio, $tamano_pagina, $suc, $perfil, $tabla) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            if ($perfil == 1) {
                $add = " ";
            } else {
                $add = "WHERE m.id_sucursal='$suc'";
            }

            $rst_select_lotes = $this->conexionObj2->consultar("SELECT m.nombre, SUM(n.cantidad), SUM(n.cantidad*precio) FROM nomina AS n " .
                    "INNER JOIN mensajeros AS m ON n.id_mensajero=m.id_mensajero $add GROUP BY n.id_mensajero LIMIT $inicio,$tamano_pagina");
            //$rst_select_lotes2="SELECT m.nombre, SUM(n.cantidad), SUM(n.cantidad*precio) FROM nomina AS n INNER JOIN mensajeros AS m ON n.id_mensajero=m.id_mensajero $add GROUP BY n.id_mensajero LIMIT $inicio,$tamano_pagina";
            //echo  $rst_select_lotes2;

            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>$" . number_format($row_select_lotes[2], 2, ',', '.') . "</td>";
                $sum = $sum + $row_select_lotes[3];
                ?>
                   <!--a href="ver_pendiente_general.php?id_user=<? echo $_GET['id_user']; ?>&suc=<? echo $_GET['suc']; ?>&id_mens=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>&nommens=<? echo $row_select_lotes[1]; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>"><? echo $row_select_lotes[3]; ?></a-->
                <?
            }
        }

        function consulta_mensajero_planilla($inicio, $tamano_pagina, $suc, $perfil, $idmsnj, $tabla) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            if ($perfil == 1) {
                //			  $add='';
                $add = "WHERE p.id_mensajero='$idmsnj' AND p.id_sucursal='$suc'";
            } else {
                //			  $add="WHERE p.fecha_planilla BETWEEN '$f1' AND '$f2' AND p.id_sucursal='$suc'";
                $add = "WHERE p.id_mensajero='$idmsnj' AND p.id_sucursal='$suc'";
            }
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT p.id_planilla, p.fecha_planilla, p.hora_planilla, m.nombre, m.id_mensajero FROM planillas as p " .
                    "inner join mensajeros as m on p.id_mensajero=m.id_mensajero $add order by id_planilla desc limit 5");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
                echo "<td valign=top class=miTable_td>";
                ?><div align="center">
                    <a href="agregar_guia.php?planilla=<? echo $row_select_lotes[0]; ?>&id_mens=<? echo $row_select_lotes[4]; ?>&tabla=<? echo $tabla; ?>" onClick="window.open('agregar_guia.php?planilla=<? echo $row_select_lotes[0]; ?>&id_mens=<? echo $row_select_lotes[4]; ?>&tabla=<? echo $tabla; ?>', 'window', 'width=400,height=280');
                    return false">
                        <img src="imagenes/add.gif"></a></div>
                <?
                echo "</td>";
            }
        }

        function lista_cliente($inicio, $tamano_pagina, $suc, $perfil, $add) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            /* if($perfil==1){
              $add='';
              }else{
              $add="WHERE id_sucursal='$suc'";
              } */
            if (!empty($add)) {
                $add2 = " and c.id_sucursal=s.id_sucursal and ci.id_ciudad=c.id_ciudad";
            } else {
                $add2 = "where c.id_sucursal=s.id_sucursal and ci.id_ciudad=c.id_ciudad";
            }
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT c.id_cliente, c.nombre, c.cod_cliente, c.nit, c.direccion, c.telefono, c.fax, c.mail, c.webpage, c.estado, c.id_ciudad, ci.nombre as nom_ciu, c.id_sucursal, s.nombre as nom_suc
FROM clientes as c, sucursales as s, ciudades as ci $add $add2 order by id_cliente LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['cod_cliente'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['nombre'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['nit'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['direccion'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['telefono'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['mail'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['nom_suc'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['nom_ciu'] . "</td>";
                echo "<td valign=middle class=miTable_td>";
                ?>
                <a href='accion_cliente.php?id=<? echo "" . $row_select_lotes['id_cliente'] . ""; ?>&tipo=1' onClick="window.open('accion_cliente.php?id=<? echo "" . $row_select_lotes['id_cliente'] . ""; ?>&tipo=1', 'window', 'width=350,height=400');
                    return false">
                    <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td width="100">
                <a href='accion_cliente.php?id=<? echo "" . $row_select_lotes['id_cliente'] . ""; ?>&tipo=2' onClick="window.open('accion_cliente.php?id=<? echo "" . $row_select_lotes['id_cliente'] . ""; ?>&tipo=2', 'window', 'width=350,height=400');
                    return false"><img src='imagenes/del.gif'></a><?
                echo "<input type=checkbox id='del_cliente' name='del_cliente[$i]' value=" . $row_select_lotes['id_cliente'] . " class=inputbox >";
                echo "</td>";
            }
        }

        function planilla($inicio, $tamano_pagina, $suc, $user, $tabla, $planilla, $id_men) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $perfil = $_SESSION['perfil'];
            if ($perfil == 1) {
                $add = "WHERE g.id_planilla='$planilla' and g.id_mensajero='$id_men'  ";
            } else {
                $add = "WHERE g.id_planilla='$planilla' and g.id_mensajero='$id_men' and g.id_sucursal=$suc  ";
            }

            $rst_select_lotes = $this->conexionObj2->consultar("SELECT guia, g.orden, g.destinatario, g.direccion, g.telefono, o.producto, g.id_estado, e.nombre as estado FROM $tabla as g inner join ordenes as o on (g.orden=o.orden) inner join estados_gestion as e on (g.id_estado=e.id_estado)  $add order by id_conse LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr><td valign=top class=miTable_td2>";
                ?>
                <A HREF='accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0]; ?>', onClick='window.open("accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0] ?>&prod=<? echo $row_select_lotes[5] ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=yes");
                    return false'><? echo $row_select_lotes[0]; ?></A>
                <?
                echo "</td><td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[4] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[7] . "</td>";
            }
        }

        function manifiesto($inicio, $tamano_pagina, $suc, $user, $tabla, $manifiesto) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $add = "WHERE id_manifiesto='$manifiesto'";
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT guia, g.orden, destinatario, direccion, telefono, o.producto FROM $tabla as g inner join ordenes as o on g.orden=o.orden $add order by id_conse LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr><td valign=top class=miTable_td2>";
                ?>
                <A HREF='accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0]; ?>', onClick='window.open("accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0] ?>&prod=<? echo $row_select_lotes[5] ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=no");
                    return false'><? echo $row_select_lotes[0]; ?></A>
                <?
                echo "</td><td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[4] . "</td>";
            }
        }

        function gestion_ods($inicio, $tamano_pagina, $user, $suc, $perfil, $add) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $tabla = "guias_proceso";
            $cons_orden = "select o.producto,o.fecha_creacion,b.orden,count(*) as total
				from ordenes as o inner join guias_proceso as b on o.orden=b.orden " . $add . " group 
				by b.orden order by id_orden desc limit " . $inicio . "," . $tamano_pagina;
            $rst_select_lotes = $this->conexionObj2->consultar($cons_orden);
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td2><A HREF='ejecuta_rastreo.php?id_user=$user&suc=$suc&ods=" . trim($row_select_lotes['orden']) . "&tabla=$tabla'>" . $row_select_lotes['orden'] . "</A></td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['producto'] . "</td>";
                echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes['fecha_creacion'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['total'] . "</td>";
            }
        }

        function planilla_seleccion($inicio, $tamano_pagina, $user, $suc, $perfil, $tabla, $ods) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            if ($perfil == 1) {
                $add = "WHERE (g.id_estado='12' OR g.id_estado=19) and g.orden='" . $ods . "'";
            } else {

                $add = "WHERE g.id_sucursal='$suc' AND (g.id_estado='12' OR g.id_estado=19) and g.orden='" . $ods . "'";
            }
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT g.cod_zona, g.nom_zona, COUNT(guia) FROM $tabla AS g
			  $add GROUP BY g.cod_zona ORDER BY g.cod_zona LIMIT $inicio,$tamano_pagina");
            $rst_select_lotes2 = "SELECT g.cod_zona, g.nom_zona, COUNT(guia) FROM $tabla AS g  $add GROUP BY g.cod_zona ORDER BY g.cod_zona LIMIT $inicio,$tamano_pagina";
            //echo $rst_select_lotes2;
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td><div align='center'><INPUT TYPE='checkbox' class='inputbox' name='registros[]' value='" . $row_select_lotes[1] . "'></td>";
            }
        }

        function gestion_ods_cliente($inicio, $tamano_pagina, $user, $suc, $perfil) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $id_cli = $_SESSION['cliente'];
            if ($perfil == 1) {
                $add = '';
            } else {
                $add = " WHERE o.id_sucursal='$suc' AND o.id_cliente='$id_cli'";
            }
            //$rst_select_tabla=$this->conexionObj2->consultar("SELECT nom_tabla FROM tablas_sucursales WHERE id_suc = '$suc'");
            //$row_select_tabla=mysql_fetch_array($rst_select_tabla);
            $tabla = "guias_proceso";
            $cons_orden = "select o.producto,o.fecha_creacion,b.orden,count(*) as total
                            from ordenes as o inner join guias_proceso as b on o.orden=b.orden " . $add . " group 
                            by b.orden order by orden desc desc limit " . $inicio . "," . $tamano_pagina;

            $rst_select_lotes = $this->conexionObj2->consultar($cons_orden);
            //echo "Error MySql:". mysql_error();
            //echo "Limit :".$inicio,$tamano_pagina;
            //$rst_select_lotes=$this->conexionObj2->consultar("SELECT * FROM ordenes as o inner join clientes as c on o.id_cliente=c.id_cliente WHERE o.tp_digita=1 $add order by id_orden desc LIMIT $inicio,$tamano_pagina");

            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td2><A HREF='ejecuta_rastreo.php?id_user=$user&suc=$suc&ods=" . $row_select_lotes['orden'] . "&tabla=$tabla'>" . $row_select_lotes['orden'] . "</A></td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['producto'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['fecha_creacion'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['total'] . "</td>";
            }
        }

        function registros_ods($inicio, $tamano_pagina, $user, $suc, $tabla, $ods, $est, $dev) {
            include("./logos.php");
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $i = 0;
            $perfil = $_SESSION['perfil'];
            $suc;
            if ($perfil == 1) {
                $add = "WHERE t.orden = '$ods' AND t.id_estado = '$est' AND t.id_devolucion = '$dev'";
            } else {
                $add = "WHERE t.id_sucursal='$suc' AND t.orden = '$ods' AND t.id_estado = '$est' AND t.id_devolucion = '$dev'";
            }
$area_ordenes='';

$field='t.guia, t.empresa, t.destinatario, t.direccion, t.telefono, t.ciudad, producto,t.identificacion,t.orden,
t.especial1,t.especial2,t.especial3,t.especial4,t.especial5,t.especial6,t.especial7,t.especial8,t.especial9,t.especial10,t.path,t.no_paquete';

if($_SESSION['area']!='0'){
    $areas=$_SESSION['area'];
	$area_ordenes=' and especial2 in('.$areas.') ';
	$field ='t.guia,t.direccion,t.Ciudad,t.especial1,t.Orden';
     $f_entrega = '00-00-0000';
}
if($_SESSION['zona']!='0'){
    $zona_ordenes=' and cod_zona="'.$_SESSION['zona'].'" ';
    $field ='t.guia,t.direccion,t.Ciudad,t.especial1,t.Orden';
     $f_entrega = '00-00-0000';
}
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT  ".$field." FROM $tabla as t inner join ordenes as o on t.orden=o.orden inner join clientes as c on t.id_cliente=c.id_cliente" .
                    " $add ".$area_ordenes.$zona_ordenes."order by t.orden desc LIMIT $inicio,$tamano_pagina");
            echo mysql_error();
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                $i++;
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>";
                $icono = "./imagenes/recursos/guia.gif";
                if (empty($row_select_lotes['path'])) {
                    $icono = "./imagenes/recursos/des_guia.gif";
                }
                ?>
                <A HREF='accion_guia.php?tipo=1', onClick='window.open("accion_guia.php?guia=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=no");
                    return false'><img src="<? echo $icono; ?>"></a>
                <? echo "</td>";
                ?>
            <td valign=top class=miTable_td><A HREF='accion_rastreo.php?tipo=1', onClick='window.open("accion_rastreo.php?guia=<? echo $row_select_lotes[0]; ?>&tipo=1&tabla=<? echo $tabla; ?>&id_suc=<? echo $suc; ?>", "window", "width=550,height=650,resizable=yes,scrollbars=yes");
                    return false'>Ver Rastreo</a>
            </td>
            <? echo "<td valign=top class=miTable_td>"; ?>
            <A HREF="accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0]; ?>", onClick='window.open("accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0] ?>&prod=<? echo $row_select_lotes[6] ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=yes");
                    return false'><? echo $row_select_lotes[0]; ?></A></td>
            <?
            //$f_entrega = $row_select_lotes[6];
            if (!empty($row_select_lotes[13])) {
                $f_entrega = date("d-m-Y", strtotime($row_select_lotes[13]));
            }
if($_SESSION['area']!='0'){

            echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>"; ##EMPRESA
            echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[2] . "</td>"; ##DESTINATARIO
            echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[3] . "</td>"; ##DIRECCION
            echo "<td valign=top class=miTable_td>" .  $row_select_lotes[4] . "</td>"; ##ESPECIAL5
}else{
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[8] . "</td>"; ##ORDEN
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>"; ##EMPRESA
            echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[2] . "</td>"; ##DESTINATARIO
            echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[3] . "</td>"; ##DIRECCION
            echo "<td valign=top class=miTable_td>" . $f_entrega . "</td>"; ##ESPECIAL5
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[4] . "</td>"; ##TELEFONO
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[5] . "</td>"; ##CIUDAD
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[7] . "</td>"; ##IDENTIFICACION

            if (!empty($Tespecial1)) {
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[9] . "</td>"; ##Especial1
            }
            if (!empty($Tespecial2)) {
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[10] . "</td>"; ##Especial2
            }
            if (!empty($Tespecial3)) {
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[11] . "</td>"; ##Especial3
            }
            if (!empty($Tespecial4)) {
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[12] . "</td>"; ##Especial4
            }
            if (!empty($Tespecial6)) {
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[14] . "</td>"; ##Especial4
            }
            if (!empty($Tespecial7)) {
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[15] . "</td>"; ##Especial4
            }
            if (!empty($Tespecial8)) {
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[16] . "</td>"; ##Especial4
            }
            if (!empty($Tespecial9)) {
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[17] . "</td>"; ##Especial4
            }
            if (!empty($Tespecial10)) {
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[18] . "</td>"; ##Especial4
            }
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[20] . "</td>"; ##No Paquete
        }
       }
    }

    function registros_devoluciones($inicio, $tamano_pagina, $user, $suc, $tabla, $id_mens, $f1, $f2) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $i = 0;
        $perfil = $_SESSION['perfil'];
        if (!empty($f1) and !empty($f2))
            $sql2 = " and  r.F16>='" . $f1 . "' AND r.F16<='" . $f2 . "' ";
        $rst_select_lotes = $this->conexionObj2->consultar("SELECT count(g.guia), g.orden, o.producto, c.nombre
				FROM $tabla as g 
				inner join rastreo_guias as r on (g.guia=r.guia) 
				INNER JOIN ordenes as o on (g.orden=o.orden)
				inner join clientes as c on (o.id_cliente=c.id_cliente)
				inner join plani_dev as p on (g.guia=p.guia) 
				inner join mensajeros as m on (p.id_mensajero=m.id_mensajero) 
				where p.id_mensajero='$id_mens' " . $sql2 . "   GROUP BY g.orden LIMIT $inicio,$tamano_pagina");

        while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
            echo "<tr class=miTable_tr>";
            echo "<td valign=top class=miTable_td>";
            ?><A HREF="accion_dev.php?tabla=<? echo $tabla; ?>&orden=<? echo trim($row_select_lotes[1]); ?>&id_mens=<? echo $id_mens; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>", onClick='window.open("accion_dev.php?tabla=<? echo $tabla; ?>&orden=<? echo trim($row_select_lotes[1]) ?>&id_mens=<? echo $id_mens; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>", "window", "width=750,height=600,toolbars=no,scrollbars=yes,resizable=yes");
                    return false'><? echo $row_select_lotes[1]; ?></A>
            <?
            echo "</td><td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
            $total_dev = $total_dev + $row_select_lotes[0];
        }
        $_POST['total_dev'] = $total_dev;
    }

    function registros_pendientes($inicio, $tamano_pagina, $user, $suc, $tabla, $id_mens, $f1, $f2,$StrCond) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $i = 0;        
        $add = " AND g.id_mensajero='$id_mens' AND r.F13>='" . $f1 . "' AND r.F13<'" . $f2 . "' ".$StrCond."";
        $rst_select_lotes = $this->conexionObj2->consultar("SELECT count(g.guia), g.orden, o.producto, c.nombre
				FROM $tabla as g 
				inner join rastreo_guias as r on (g.guia=r.guia)
				inner join ordenes as o on (g.orden=o.orden)
				inner join clientes as c on (o.id_cliente=c.id_cliente)
				WHERE o.tp_digita=1 $add  GROUP BY g.orden LIMIT $inicio,$tamano_pagina");

        while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
            echo "<tr class=miTable_tr>";
            echo "<td valign=top class=miTable_td>";
            $Cond=str_replace("'","",$StrCond);
            ?><A TARGET = "_blank" HREF="detalle_guias.php?StrCond=<? echo $Cond; ?>&orden=<? echo trim($row_select_lotes[1]); ?>&id_mens=<? echo $id_mens; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>"><? echo $row_select_lotes[1];?></A>
            <?
            echo "</td><td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
        }
    }

    function registros_pendientes2($inicio, $tamano_pagina, $user, $suc, $tabla, $id_suc, $f1, $f2) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $i = 0;
        $perfil = $_SESSION['perfil'];
        if ($perfil == 1) {
            $add = "WHERE g.id_estado = '13' AND r.F13>='$f1' AND r.F13<'$f2'";
        } else {
            $add = "WHERE g.id_sucursal='$id_suc' AND g.id_estado = '13' AND r.F13>='$f1' AND r.F13<'$f2'";
        }
        $rst_select_lotes = $this->conexionObj2->consultar("SELECT count(g.guia), g.orden, o.producto, c.nombre
			   FROM $tabla as g 
			   inner join rastreo_guias as r on (g.guia=r.guia)
			   inner join ordenes as o on (g.orden=o.orden)
				inner join sucursales as s on (o.id_sucursal=s.id_sucursal)
				inner join clientes as c on o.id_cliente=c.id_cliente
			   $add  GROUP BY g.orden LIMIT $inicio,$tamano_pagina");

        while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
            echo "<tr class=miTable_tr>";
            echo "<td valign=top class=miTable_td>"; //.$row_select_lotes[1];
            ?><A HREF="accion_pendientes_suc.php?tabla=<? echo $tabla; ?>&orden=<? echo trim($row_select_lotes[1]); ?>&id_suc=<? echo $id_suc; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>", onClick='window.open("accion_pendientes_suc.php?tabla=<? echo $tabla; ?>&orden=<? echo trim($row_select_lotes[1]) ?>&id_suc=<? echo $id_suc; ?>&f1=<? echo $f1; ?>&f2=<? echo $f2; ?>", "window", "width=750,height=600,toolbars=no,scrollbars=yes,resizable=yes");
                    return false'><? echo $row_select_lotes[1]; ?></A>
            <?
            echo "</td><td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[0] . "</td>";
            $total = $total + $row_select_lotes[0];
        }
        //$_SESSION['pend_total']=$total;
    }

    function gestion($filas, $ods, $tabla, $user, $suc) {
$area_ordenes='';
if($_SESSION['area']!='0'){
	$area_ordenes=' and especial2 in('.$_SESSION['area'].') ';
}
//echo $area_ordenes;
$zona_ordenes='';
if($_SESSION['zona']!=0){
    $zona_ordenes=' and cod_zona="'.$_SESSION['zona'].'" ';
}
        $total_ods = $filas;
        ?>
        <script>

            function cambiarDisplay(id) {
                if (!document.getElementById)
                    return false;
                fila = document.getElementById(id);
                if (fila.style.display != "none") {
                    fila.style.display = "none"; //ocultar fila 
                } else {
                    fila.style.display = ""; //mostrar fila 
                }
            }

        </script>
        <?
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $perfil = $_SESSION['perfil'];
        $suc;
        if ($perfil == 1) {
            $add = '';
        } else {
            $add = " AND g.id_sucursal = '$suc'";
        }

$sql = "SELECT id_estado,nombre,space(11) as total  from estados_gestion where id_estado in (12,13,14,15,16,21,22,23)  ORDER BY id_estado ";
        $resultado = $this->conexionObj2->consultar($sql);

        while ($row = mysql_fetch_array($resultado)) {
            $array_codigos[] = $row['nombre'];

            $codigo = $row['id_estado'];
            $strsql = "SELECT count(*) FROM guias_proceso WHERE id_estado = '" . $codigo . "' and orden='" . $ods . "'".$area_ordenes.$zona_ordenes;
            $rest = $this->conexionObj2->consultar($strsql);
            $reg = mysql_fetch_array($rest);
            $array_totales[] = $reg[0];
            $row['total'] = $reg[0];
        }

///Calcula el total de entregadas y el porcentaje de las mismas.
        $cntent = $array_totales[2] + $array_totales[3]+$array_totales[5] + $array_totales[7];
        if ($cntent > 0) {
            $tmp = ($cntent / $total_ods) * 100;
            $porent = substr($tmp, 0, 4);
        } else {
            $porent = 0;
        }

        if ($porent > 0 and $porent < 1) {
            $porent = 1;
        }

        //////calculo el total por estado.                     
        $porcencentro = 0;
        $totalcentro = 0;
        for ($x = 0; $x <= count($array_codigos); $x++) {
            $tmp = ($array_totales[$x] / $total_ods) * 100;
            $porcentaje = substr($tmp, 0, 4);
            if ($x == 0) {
                $totalcentro = $totalcentro + $array_totales[$x];
                $porcencentro = $porcencentro + $porcentaje;
            }

            if ($x >= 0 and $x <= 1) {
                $totalproceso = $totalproceso + $array_totales[$x];
                $porcenproceso = $porcenproceso + $porcentaje;
            }


            if ($x >= 4 and $x <= 4) {
                $totaldevo = $totaldevo + $array_totales[$x];
                $porcendevo = $porcendevo + $porcentaje;
            }

            if ($x >= 6 and $x <= 6) {
                $totalnov = $totalnov + $array_totales[$x];
                $porcenov = $porcenov + $porcentaje;
            }
        }
///////////////////////////////////////////////////////////////////////
        if ($porcendevo > 0 and $porcendevo < 1) {
            $porcendevo = 1;
        }

        if ($porcenproceso > 0 and $porcenproceso < 1) {
            $porcenproceso = 1;
        }

        if ($porcencentro > 0 and $porcencentro < 1) {
            $porcencentro = 1;
        }

        $datograph = $cntent . "," . $totaldevo . "," . $totalproceso;
        $total_real_porcentaje = 0;

        for ($i = 0; $i <= count($array_codigos); $i++) {
            /* calculo de % por estado */
            $tmp = ($array_totales[$i] / $total_ods) * 100;
            $porcentaje = substr($tmp, 0, 4);
            $total_real_porcentaje = $total_real_porcentaje + $porcentaje;
        }
$query="select count(*),'$array_codigos[0]','12','$ods' AS orden from guias_proceso where id_estado=12 ".$area_ordenes.$zona_ordenes." and orden='$ods'
                       union select count(*),'$array_codigos[1]',13," . $ods . " AS orden  from guias_proceso where id_estado=13 ".$area_ordenes." and orden='$ods'
                       union select count(*),'$array_codigos[2]',14," . $ods . " AS orden  from guias_proceso where id_estado=14 ".$area_ordenes."and orden='$ods'
                       union select count(*),'$array_codigos[3]',15," . $ods . " AS orden from guias_proceso where id_estado=15 ".$area_ordenes."and orden='$ods'
union select count(*),'$array_codigos[5]',21," . $ods . " AS orden from guias_proceso where id_estado=21 ".$area_ordenes.$zona_ordenes."and orden='$ods'
union select count(*),'$array_codigos[6]',22," . $ods . " AS orden from guias_proceso where id_estado=22 ".$area_ordenes.$zona_ordenes."and orden='$ods'
union select count(*),'$array_codigos[7]',23," . $ods . " AS orden from guias_proceso where id_estado=23 ".$area_ordenes.$zona_ordenes."and orden='$ods'";
//echo $query;
        $rst_select_lotes = $this->conexionObj2->consultar($query);

        $valida_e = mysql_num_rows($rst_select_lotes);

        if ($filas >= 1) {
            $titulo = 0;
            $pband = 0;
            $y = 1;
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                $titulo = $titulo + 1;
                if ($valida_e >= 1 && $titulo == 1 && $row_select_lotes[2] != 14 && $row_select_lotes[2] != 21 && $row_select_lotes[2] != 22 && $row_select_lotes[2] != 23 && $row_select_lotes[2] != 15) {
                    ?>
                    <tr class=miTable_tr>
                        <td  colspan=1 BGCOLOR="gray" style="cursor: hand" onClick="cambiarDisplay('fila1');
                            cambiarDisplay('fila2')">&nbsp;Operaciones</td>
                        <td  align="right" BGCOLOR="gray"><?php echo number_format($totalproceso, 0, '', '.'); ?>&nbsp;&nbsp;</td>
                        <td  align="right" BGCOLOR="gray"><?php echo number_format($porcenproceso, 0, '', '.'); ?>%&nbsp;&nbsp;</td>
                        <td  align="right" BGCOLOR="gray">&nbsp;&nbsp;</td>
                    </tr>
                    <?
                    $filas_oper = 1;
                }

                if ($row_select_lotes[2] == 14 or $row_select_lotes[2] == 15 or $row_select_lotes[2] == 21 or $row_select_lotes[2] == 23) {
                    if ($pband == 0) {
                        $pband = 1;
                        ?>
                        <tr class=miTable_tr>
                            <td BGCOLOR="#2E2E2E" colspan=1 style="cursor: hand" onClick="cambiarDisplay('fila3');
                                cambiarDisplay('fila4');
cambiarDisplay('fila5')
cambiarDisplay('fila7')">&nbsp;Entregadas</td>
                            <td align="right" BGCOLOR="#2E2E2E"><?php echo number_format($cntent, 0, '', '.'); ?>&nbsp;&nbsp;</td>
                            <td align="right" BGCOLOR="#2E2E2E"><?php echo number_format($porent, 0, '', '.'); ?>%&nbsp;&nbsp;</td>
                            <td align="right" BGCOLOR="#2E2E2E">&nbsp;&nbsp;</td>
                        </tr>

                        <?
                    }
                }


                
                $nomdiv = "fila" . $y;

                echo '<tr class=miTable_tr id=' . $nomdiv . ' style="display: none">';

                echo "<td valign=top class=miTable_td2><A HREF='ver_registros.php?id_user=$user&suc=$suc&ods=" . trim($row_select_lotes['orden']) . "&tabla=$tabla&est=$row_select_lotes[2]&dev=$row_select_lotes[4]&nomest=$row_select_lotes[1]'>" . $row_select_lotes[1] . "</A></td>";
                $array_nombre[] = $row_select_lotes[1];
                echo "<td valign=top class=miTable_td align='right'>" . $row_select_lotes[0] . "&nbsp;</td>";
                $array_cantidad[] = $row_select_lotes[0];
                $tmp = ($row_select_lotes[0] / $filas) * 100;
                $porcentaje = substr($tmp, 0, 4);
                $total_real_porcentaje = $total_real_porcentaje + $porcentaje;
                echo "<td valign=top class=miTable_td align='right'>" . $porcentaje . " %&nbsp;</td>";
                $array_porc[] = $porcentaje;
                $total = $total + $row_select_lotes[0];
                $colspan = $colspan + 1;
                echo "<td valign=top class=miTable_td><div align='center'>";
                $nombcsv = trim($row_select_lotes[1]) . '_' . trim($ods) . "_" . date('Ymd');
                echo "<a href='export_csv.php?nomcsv=$nombcsv&registro=2&estado=$row_select_lotes[2]&dev=$row_select_lotes[4]' onclick=\"displayStaticMessage('<p align=center><font color=#008400><b>Espere por Favor se esta Generando Archivo CSV</b><br><img src=\'imagenes/txt_icon.gif\'><br>Al Terminar Proceso Cerrar Ventana </font><br><input type=submit value=Cerrar class=inputbox onclick=\'closeMessage();return false\'></p>',false)\" title='Exportar CSV Estados'><img src='imagenes/txt_icon.gif'></a></div></td>";
$y++;            
}





            /////////////Imprime Tabla para novedad inicial.
            /*$rst_select_lotes = $this->conexionObj2->consultar("SELECT count(g.guia), e.nombre, g.id_estado,
                            g.orden FROM $tabla as g inner join estados_gestion as e on 
                            (g.id_estado=e.id_estado) WHERE g.orden = '$ods' AND g.id_estado=18 ".$area_ordenes.$zona_ordenes." group by g.id_estado");

            $valida_d = mysql_num_rows($rst_select_lotes);
            if ($valida_d >= 1) {
                ?>
                <tr class=miTable_tr>
                    <td BGCOLOR="#31B404" colspan=1 style="cursor: hand" onClick="cambiarDisplay('ini1');">&nbsp;Novedad Inicial</td>
                    <td BGCOLOR="#31B404" align="right"><?php echo number_format($totalnov, 0, '', '.'); ?>&nbsp;&nbsp;</td>
                    <td BGCOLOR="#31B404" align="right"><?php echo number_format($porcenov, 0, '', '.'); ?>%&nbsp;&nbsp;</td>
                    <td BGCOLOR="#31B404" align="right">&nbsp;&nbsp;</td>
                </tr>
                <?
                while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                    echo '<tr class=miTable_tr id="ini1" style="display: none">';
                    echo "<td valign=top class=miTable_td><A HREF='ver_registros.php?id_user=$user&suc=$suc&ods=" . $row_select_lotes['orden'] . "&tabla=$tabla&est=$row_select_lotes[2]&nomest=$row_select_lotes[1]'>" . $row_select_lotes[1] . "</A></td>";
                    $array_nombre[] = $row_select_lotes[3];
                    echo "<td valign=top class=miTable_td align='right'>" . $row_select_lotes[0] . "&nbsp;</td>";
                    $array_cantidad[] = $row_select_lotes[0];
                    $tmp = ($row_select_lotes[0] / $filas) * 100;
                    $porcentaje = substr($tmp, 0, 4);
                    $total_real_porcentaje = $total_real_porcentaje + $porcentaje;
                    echo "<td valign=top class=miTable_td align='right'>" . $porcentaje . " %&nbsp;</td>";
                    $array_porc[] = $porcentaje;
                    $total = $total + $row_select_lotes[0];
                    $colspan1 = $colspan1 + 1;
                    echo "<td valign=top class=miTable_td><div align='center'>";
                    //echo "<a href='servicio_cliente.php?tabla=$tabla&registro=2&estado=$row_select_lotes[2]' onclick=\"displayStaticMessage('<p align=center><font color=#008400><b>Espere por Favor se esta Generando Archivo XLS</b><br><img src=\'imagenes/xls_icon.gif\'><br>Al Terminar Proceso Cerrar Ventana </font><br><input type=submit value=Cerrar class=inputbox onclick=\'closeMessage();return false\'></p>',false)\" title='Exportar XLS Devoluciones'><img src='imagenes/xls_icon.gif'></a> ";
                    //echo "<a href='csv_rastreo.php?tabla=$tabla&registro=2&estado=$row_select_lotes[2]&dev=$row_select_lotes[4]&nomcsv=$row_select_lotes[1]".$ods."' onclick=\"displayStaticMessage('<p align=center><font color=#008400><b>Espere por Favor se esta Generando Archivo CSV</b><br><br>Al Terminar Proceso Cerrar Ventana </font><br><input type=submit value=Cerrar class=inputbox onclick=\'closeMessage();return false\'></p>',false)\" title='Exportar CSV'><img src='imagenes/recursos/txt.png'></a> ";
                    $nombcsv = 'NovedadInicial_' . trim($ods) . "_" . date('Ymd');
                    echo "<a href='export_csv.php?nomcsv=$nombcsv&registro=2&estado=$row_select_lotes[2]' onclick=\"displayStaticMessage('<p align=center><font color=#008400><b>Espere por Favor se esta Generando Archivo CSV</b><br><img src=\'imagenes/txt_icon.gif\'><br>Al Terminar Proceso Cerrar Ventana </font><br><input type=submit value=Cerrar class=inputbox onclick=\'closeMessage();return false\'></p>',false)\" title='Exportar CSV Devoluciones'><img src='imagenes/txt_icon.gif'></a></div></td>";
                }
            }*/
if($tabla<>"guias_proceso"){
$area_ordenes="";
$zona_ordenes="";
}

            ///////Imprime el titulo para devolucion si estas existen. 
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT count(g.guia), e.nombre, g.id_estado, 
                            d.nombre, g.id_devolucion, g.orden FROM $tabla as g inner join estados_gestion as e on 
                            (g.id_estado=e.id_estado) inner join devoluciones as d on (g.id_devolucion=d.id_devolucion) 
                            left join rastreo_guias as rg on (g.guia=rg.guia) WHERE g.orden = '$ods' 
                            AND g.id_estado=16 $add ".$area_ordenes.$zona_ordenes." group by g.id_estado, id_devolucion ORDER BY d.nombre");

            $valida_d = mysql_num_rows($rst_select_lotes);

            if ($valida_d >= 1) {
                ?>
                <tr class=miTable_tr>
                    <td BGCOLOR="#C10001" colspan=1 style="cursor: hand" onClick="cambiarDisplay('dev1');
                        cambiarDisplay('dev2');
                        cambiarDisplay('dev3');
                        cambiarDisplay('dev4');
                        cambiarDisplay('dev5');
                        cambiarDisplay('dev6');
                        cambiarDisplay('dev7');
                        cambiarDisplay('dev8');
                        cambiarDisplay('dev9');
                        cambiarDisplay('dev10');
                        cambiarDisplay('dev11');
                        cambiarDisplay('dev12');
                        cambiarDisplay('dev13');
                        cambiarDisplay('dev14');
                        cambiarDisplay('dev15');">&nbsp;Devoluciones</td>
                    <td BGCOLOR="#C10001" align="right"><?php echo number_format($totaldevo, 0, '', '.'); ?>&nbsp;&nbsp;</td>
                    <td BGCOLOR="#C10001" align="right"><?php echo number_format($porcendevo, 0, '', '.'); ?>%&nbsp;&nbsp;</td>
                    <td BGCOLOR="#C10001" align="right">&nbsp;&nbsp;</td>
                </tr>
                    <?
                }
                //////Imprime los estados de devolución.
                $z = 0;
                while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                    $z++;
                    $nomdiv = "dev" . $z;
                    echo '<tr class=miTable_tr id=' . $nomdiv . ' style="display: none">';
                    echo "<td valign=top class=miTable_td><A HREF='ver_registros.php?id_user=$user&suc=$suc&ods=" . $row_select_lotes['orden'] . "&tabla=$tabla&est=$row_select_lotes[2]&dev=$row_select_lotes[4]&nomest=$row_select_lotes[1]'>" . $row_select_lotes[3] . "</A></td>";
                    $array_nombre[] = $row_select_lotes[3];
                    echo "<td valign=top class=miTable_td align='right'>" . $row_select_lotes[0] . "&nbsp;</td>";
                    $array_cantidad[] = $row_select_lotes[0];
                    $tmp = ($row_select_lotes[0] / $filas) * 100;
                    $porcentaje = substr($tmp, 0, 4);
                    $total_real_porcentaje = $total_real_porcentaje + $porcentaje;
                    echo "<td valign=top class=miTable_td align='right'>" . $porcentaje . "%&nbsp;</td>";
                    $array_porc[] = $porcentaje;
                    $total = $total + $row_select_lotes[0];
                    $colspan1 = $colspan1 + 1;
                    echo "<td valign=top class=miTable_td><div align='center'>";
                    $nombcsv = $row_select_lotes[3] . '_' . trim($ods) . "_" . date('Ymd');
                    echo "<a href='export_csv.php?nomcsv=$nombcsv&registro=2&estado=$row_select_lotes[2]&dev=$row_select_lotes[4]' onclick=\"displayStaticMessage('<p align=center><font color=#008400><b>Espere por Favor se esta Generando Archivo CSV</b><br><img src=\'imagenes/txt_icon.gif\'><br>Al Terminar Proceso Cerrar Ventana </font><br><input type=submit value=Cerrar class=inputbox onclick=\'closeMessage();return false\'></p>',false)\" title='Exportar CSV Devoluciones'><img src='imagenes/txt_icon.gif'></a></div></td>";
                }



              ///////Imprime el titulo para devolucion si estas existen. 
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT count(g.guia), e.nombre, g.id_estado, 
                            d.nombre, g.id_devolucion, g.orden FROM $tabla as g inner join estados_gestion as e on 
                            (g.id_estado=e.id_estado) inner join devoluciones as d on (g.id_devolucion=d.id_devolucion) 
                            left join rastreo_guias as rg on (g.guia=rg.guia) WHERE g.orden = '$ods' 
                            AND g.id_estado=22 $add ".$area_ordenes.$zona_ordenes." group by g.id_estado, id_devolucion ORDER BY d.nombre");

            $valida_d = mysql_num_rows($rst_select_lotes);

            if ($valida_d >= 1) {
                ?>
                <tr class=miTable_tr>
                    <td BGCOLOR="#31B404" colspan=1 style="cursor: hand" onClick="cambiarDisplay('devF1');
                        cambiarDisplay('devF2');
                        cambiarDisplay('devF3');
                        cambiarDisplay('devF4');
                        cambiarDisplay('devF5');
                        cambiarDisplay('devF6');
                        cambiarDisplay('devF7');
                        cambiarDisplay('devF8');
                        cambiarDisplay('devF9');
                        cambiarDisplay('devF10');
                        cambiarDisplay('devF11');
                        cambiarDisplay('devF12');
                        cambiarDisplay('devF13');
                        cambiarDisplay('devF14');
                        cambiarDisplay('devF15');">&nbsp;Devoluciones Fuera de Tiempo</td>
                    <td BGCOLOR="#31B404" align="right" class="datacant"><?php //echo number_format($totaldevo, 0, '', '.'); ?>&nbsp;&nbsp;</td>
                    <td BGCOLOR="#31B404" align="right"><?php //echo number_format($porcendevo, 0, '', '.'); ?>%&nbsp;&nbsp;</td>
                    <td BGCOLOR="#31B404" align="right">&nbsp;&nbsp;</td>
                </tr>
                    <?
                }
                //////Imprime los estados de devolución.
                $z = 0;
                $to_dev_ft = 0;
                while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
$to_dev_ft = $to_dev_ft + $row_select_lotes[0];
echo "<script>$('.datacant').text(".$to_dev_ft.")</script>";
                    $z++;
                    $nomdiv = "devF" . $z;
                    echo '<tr class=miTable_tr id=' . $nomdiv . ' style="display: none">';
                    echo "<td valign=top class=miTable_td><A HREF='ver_registros.php?id_user=$user&suc=$suc&ods=" . $row_select_lotes['orden'] . "&tabla=$tabla&est=$row_select_lotes[2]&dev=$row_select_lotes[4]&nomest=$row_select_lotes[1]'>" . $row_select_lotes[3] . "</A></td>";
                    $array_nombre[] = $row_select_lotes[3];
                    echo "<td valign=top class=miTable_td align='right'>" . $row_select_lotes[0] . "&nbsp;</td>";
                    $array_cantidad[] = $row_select_lotes[0];
                    $tmp = ($row_select_lotes[0] / $filas) * 100;
                    $porcentaje = substr($tmp, 0, 4);
                    $total_real_porcentaje = $total_real_porcentaje + $porcentaje;
                    echo "<td valign=top class=miTable_td align='right'>" . $porcentaje . "%&nbsp;</td>";
                    $array_porc[] = $porcentaje;
                    //$total = $total + $row_select_lotes[0];
                    $colspan1 = $colspan1 + 1;
                    echo "<td valign=top class=miTable_td><div align='center'>";
                    $nombcsv = $row_select_lotes[3] . '_' . trim($ods) . "_" . date('Ymd');
                    echo "<a href='export_csv.php?nomcsv=$nombcsv&registro=2&estado=$row_select_lotes[2]&dev=$row_select_lotes[4]' onclick=\"displayStaticMessage('<p align=center><font color=#008400><b>Espere por Favor se esta Generando Archivo CSV</b><br><img src=\'imagenes/txt_icon.gif\'><br>Al Terminar Proceso Cerrar Ventana </font><br><input type=submit value=Cerrar class=inputbox onclick=\'closeMessage();return false\'></p>',false)\" title='Exportar CSV Devoluciones'><img src='imagenes/txt_icon.gif'></a></div></td>";
                }



                //////Total de la orden.
                echo "<tr class=miTable_tr><td class=miTable_th1>Total</td><td align='right' class=miTable_th1>$total</td><td class=miTable_th1 align='right'>100 %</td><td class=miTable_th1>";
                echo "<div align='center'>";
                //echo "<a href='csv_rastreo.php?tabla=$tabla&registro=2&estado=T&dev=0&nomcsv=Total".$ods."' onclick=\"displayStaticMessage('<p align=center><font color=#008400><b>Espere por Favor se esta Generando Archivo CSV</b><br><br>Al Terminar Proceso Cerrar Ventana </font><br><input type=submit value=Cerrar class=inputbox onclick=\'closeMessage();return false\'></p>',false)\" title='Exportar CSV General'><img src='imagenes/recursos/txt.png'></a> ";
                $nombcsv = 'Total_' . trim($ods) . "_" . date('Ymd');
                echo "<a href='export_csv.php?nomcsv=$nombcsv&registro=2&estado=T&dev=0' onclick=\"displayStaticMessage('<p align=center><font color=#008400><b>Espere por Favor se esta Generando Archivo CSV</b><br><img src=\'imagenes/txt_icon.gif\'><br>Al Terminar Proceso Cerrar Ventana </font><br><input type=submit value=Cerrar class=inputbox onclick=\'closeMessage();return false\'></p>',false)\" title='Exportar CSV General'><img src='imagenes/txt_icon.gif'></a></div></td></tr></table></CENTER>";
                echo "</div></td></tr></table></CENTER>";
                ?>			  	
			  		                
            <center>
                <br>
                <table border="1">
                    <td>    
                <?
                if ($totalnov > 0) {
                    ?>
                            <img src="graficas/tarta4d.php?numoip=<? echo $ods; ?>&ent=<?php echo $porent; ?>&dev=<?php echo $porcendevo; ?>&dis=<?php echo $porcenproceso; ?>&nov=<?php echo $porcenov; ?>">        
                    <?
                } else {
                    ?>
                            <img src="graficas/tarta3d.php?numoip=<? echo $ods; ?>&ent=<?php echo $porent; ?>&dev=<?php echo $porcendevo; ?>&dis=<?php echo $porcenproceso; ?>">
                    <?
                }
                ?>                
                    </td>
                </table>
            </center>

                <?
            }
        }

        function lista_ordenes($inicio, $tamano_pagina, $suc, $add) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $perfil = $_SESSION['perfil'];
            $suc;
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT o.id_orden, orden, o.fecha_creacion, o.hora_creacion,        o.producto, o.c_reportada,
       o.c_nacional, o.c_urbana, o.c_internacional, o.c_poblaciones, o.c_total, o.bd, 
       o.impresion, o.empaque, o.labels, o.bolsa, o.otros, o.observaciones, o.pendiente_recoger, 
       o.recogida_fecha ,o.recogida_hora ,o.cerrada, o.cerrada_por, o.cerrada_fecha, o.cerrada_hora, 
       o.id_sucursal, o.id_usuario, o.id_cliente, o.peso, o.valor, o.tp_digita, o.est_digita, 
       o.cnt_labels, o.cnt_x_label, s.nombre as nom_suc, c.nombre as nom_clie 
	   FROM ordenes as o 
            inner join sucursales as s on (o.id_sucursal=s.id_sucursal)
			inner join clientes as c on (o.id_cliente=c.id_cliente)
	   WHERE o.tp_digita=1 $add order by o.orden  desc LIMIT $inicio,$tamano_pagina");
            //$rst_select_lotes2="SELECT * FROM ordenes as o $add order by orden LIMIT $inicio,$tamano_pagina";
            //echo  $rst_select_lotes2;
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['orden'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['nom_clie'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['producto'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['nom_suc'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['observaciones'] . "</td>";
                echo "<td valign=middle class=miTable_td>";
                ?>
            <a href='accion_orden.php?orden=<? echo "" . trim($row_select_lotes['orden']) . ""; ?>&tipo=1' onClick="window.open('accion_orden.php?orden=<? echo "" . trim($row_select_lotes['orden']) . ""; ?>&tipo=1&suc=<? echo $suc; ?>', 'window', 'width=450,height=600');
                    return false">
                <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td width="50">
                <a href='accion_orden.php?orden=<? echo "" . $row_select_lotes['orden'] . ""; ?>&tipo=2' onClick="window.open('accion_orden.php?orden=<? echo "" . $row_select_lotes['orden'] . ""; ?>&tipo=2&suc=<? echo $suc; ?>', 'window', 'width=450,height=600');
                    return false">
                    <img src='imagenes/del.gif'></a>
                <?
                echo "<input type=checkbox id='del_or' name='del_or[$i]' value=" . $row_select_lotes['orden'] . " class=inputbox >";
                echo "</td>";
            }
        }

        function lista_ordenes_cliente($inicio, $tamano_pagina, $suc, $user, $cliente, $f1, $f2, $tabla) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $perfil = $_SESSION['perfil'];
            if ($perfil == 1) {
                if ($f1 == '') {
                    $add = "WHERE o.id_cliente='" . $cliente . "' AND o.fecha_creacion = '" . $f2 . "' GROUP BY o.orden DESC";
                } elseif ($f2 == '') {
                    $add = "WHERE o.id_cliente='" . $cliente . "' AND o.fecha_creacion = '" . $f1 . "' GROUP BY o.orden DESC";
                } else {
                    $add = "WHERE o.id_cliente='" . $cliente . "' AND o.fecha_creacion BETWEEN '" . $f1 . "' AND '" . $f2 . "' GROUP BY g.orden DESC";
                }
            } else {
                if ($f1 == '') {
                    $add = "WHERE o.id_sucursal='$suc' AND o.id_cliente='" . $cliente . "' AND o.fecha_creacion = '" . $f2 . "' GROUP BY o.orden DESC";
                } elseif ($f2 == '') {
                    $add = "WHERE o.id_sucursal='$suc' AND o.id_cliente='" . $cliente . "' AND o.fecha_creacion = '" . $f1 . "' GROUP BY o.orden DESC";
                } else {
                    $add = "WHERE o.id_sucursal='$suc' AND o.id_cliente='" . $cliente . "' AND o.fecha_creacion BETWEEN '" . $f1 . "' AND '" . $f2 . "' GROUP BY g.orden DESC";
                }
            }
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT g.orden, o.producto, o.fecha_creacion, count(guia) " .
                    "FROM $tabla as g inner join ordenes as o on g.orden=o.orden " .
                    "$add LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                $rst_contar = $this->conexionObj2->consultar("SELECT count(guia) FROM $tabla WHERE orden = '" . $row_select_lotes[0] . "' AND (id_estado = '14' OR id_estado = '15') ");
                $row_contar = mysql_fetch_array($rst_contar);
                $rst_contar_dev = $this->conexionObj2->consultar("SELECT count(guia) FROM $tabla WHERE orden = '" . $row_select_lotes[0] . "' AND id_estado = '16'");
                $row_contar_dev = mysql_fetch_array($rst_contar_dev);
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td><A HREF='ejecuta_rastreo.php?id_user=$user&suc=$suc&ods=" . $row_select_lotes[0] . "&tabla=$tabla&init=2&f1=$f1&f2=$f2&clienteid=$cliente'>" . $row_select_lotes[0] . "</A></td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
                echo "<td valign=top class=miTable_td>" .
                "<a HREF='ejecuta_rastreo.php?id_user=$user&suc=$suc&ods=" . $row_select_lotes[0] . "&tabla=$tabla&init=2&f1=$f1&f2=$f2&clienteid=$cliente'>ver estado</a>";
                echo "</td>";
                echo "<td valign=middle class=miTable_td><div align=center>";
                if ($row_contar[0] == $row_select_lotes[3]) {
                    echo '<img src="imagenes/sobre.gif"></div>';
                } else {
                    echo $row_contar[0];
                }
                echo "</td>";
                echo "<td valign=middle class=miTable_td><div align=center>";
                echo $row_contar_dev[0];
                echo "</div></td>";
            }
        }

        function lista_guias_reenvios($inicio, $tamano_pagina, $suc, $user, $orden, $tabla, $campo, $f1, $f2) {
            include ("./logos.php");
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $perfil = $_SESSION['perfil'];
            if ($perfil == 1) {
                $add = "where date(F17)>='" . $f1 . "' and date(F17)<='" . $f2 . "' group by g.guia ORDER BY g.orden DESC";
            } else {
                $add = "where date(F17)>='" . $f1 . "' and date(F17)<='" . $f2 . "' group by g.guia ORDER BY g.orden DESC";
                /////PENDIENTE FILTRAR POR SUCURSAL
            }

            $rst_select_lotes = $this->conexionObj2->consultar("select g.guia, g.empresa, g.destinatario, g.direccion, g.telefono,
 		 g.ciudad,g.identificacion,g.fecha_cargue,g.especial2,g.especial3,g.especial4,g.especial5,g.orden,e.nombre
 		  FROM $tabla as g inner join estados_gestion as e
			   on g.id_estado=e.id_estado inner join reenvio as b on (g.guia=b.guia) $add LIMIT $inicio,$tamano_pagina");

            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>";
                ?>
                <A HREF='accion_guia.php?tipo=1', onClick='window.open("accion_guia.php?guia=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=no");
                    return false'><? echo $row_select_lotes[0]; ?></a></td>
                
                <td valign=top class=miTable_td>
                <A HREF='accion_rastreo.php?tipo=1', onClick='window.open("accion_rastreo.php?guia=<? echo $row_select_lotes[0]; ?>&tipo=1&tabla=<? echo $tabla; ?>&id_suc=<? echo $suc; ?>", "window", "width=550,height=650,resizable=yes,scrollbars=yes");
                        return false'>Ver Rastreo</a></td>
                    
                <?
                

                $f_entrega = '00-00-0000';
                if (!empty($row_select_lotes[16]) and $row_select_lotes[16] != '0000-00-00') {
                    $f_entrega = date("d-m-Y", strtotime($row_select_lotes[16]));
                }

                echo "<td valign=top class=miTable_td>" . $row_select_lotes[13] . "</td>"; ##Estado
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[12] . "</td>"; ##Orden                                
                echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[7] . "</td>"; ##fecha cargue                
                echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[2] . "</td>"; ##DESTINATARIO
                echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[3] . "</td>"; ##DIRECCION
                echo "<td valign=top class=miTable_td nowrap>" . $f_entrega . "</td>"; ##ESPECIAL5                
                echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[5] . "</td>"; ##CIUDAD
//                if (!empty($Tespecial1)) {
//                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[7] . "</td>"; ##Especial1
//                }
//                if (!empty($Tespecial2)) {
//                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[8] . "</td>"; ##Especial2
//                }
//                if (!empty($Tespecial3)) {
//                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[9] . "</td>"; ##Especial3
//                }
//                if (!empty($Tespecial4)) {
//                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[10] . "</td>"; ##Especial4
//                }
//                if ($perfil != 5) {
//                    echo "<td valign=top class=miTable_td>";
//                    echo "</td>";
//                }//fin del if del perfil
            }
        }

        function lista_guias_consulta($inicio, $tamano_pagina, $suc, $user, $valor, $campo, $tabla, $tp_consulta) {
            include ("./logos.php");
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $perfil = $_SESSION['perfil'];
            if ($tp_consulta == '2') {
                $tp_operador = " LIKE '";
                $tp_operador2 = "%'";
            } else {
                $tp_operador = "='";
                $tp_operador2 = "'";
            }
            if ($perfil == 1) {
                $add = "WHERE g." . $campo . $tp_operador . $valor . $tp_operador2 . " ORDER BY g.guia ASC";
            } else {
                $add = "WHERE g." . $campo . $tp_operador . $valor . $tp_operador2 . " AND g.id_sucursal='" . $suc . "' ORDER BY g.guia ASC";
            }
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT g.guia, g.empresa, g.destinatario, g.direccion, g.telefono, g.ciudad, g.id_mensajero, s.nombre, g.id_planilla, e.nombre, g.id_devolucion,g.identificacion,
			  especial1,especial2,especial3,especial4,especial5,g.orden  " .
                    "FROM $tabla as g INNER JOIN estados_gestion AS e ON g.id_estado = e.id_estado INNER JOIN sucursales AS s ON g.id_sucursal = s.id_sucursal " .
                    "$add LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>";
                ?>
                <A HREF='accion_guia.php?tipo=1', onClick='window.open("accion_guia.php?guia=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=no");
                    return false'><? echo $row_select_lotes[0]; ?></a>
                <?
                echo "</td>";

                $f_entrega = '00-00-0000';
                if (!empty($row_select_lotes[16]) and $row_select_lotes[16] != '0000-00-00') {
                    $f_entrega = date("d-m-Y", strtotime($row_select_lotes[16]));
                }

                echo "<td valign=top class=miTable_td>" . $row_select_lotes[17] . "</td>"; ##Orden
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[9] . "</td>"; ##Estado
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>"; ##EMPRESA
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>"; ##DESTINATARIO
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>"; ##DIRECCION
                echo "<td valign=top class=miTable_td>" . $f_entrega . "</td>"; ##ESPECIAL5
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[4] . "</td>"; ##TELEFONO
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[11] . "</td>"; ##IDENTIFICACION
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[5] . "</td>"; ##CIUDAD
                if (!empty($Tespecial1)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[12] . "</td>"; ##Especial1
                }
                if (!empty($Tespecial2)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[13] . "</td>"; ##Especial2
                }
                if (!empty($Tespecial3)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[14] . "</td>"; ##Especial3
                }
                if (!empty($Tespecial4)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[15] . "</td>"; ##Especial4
                }

                $rst_selectMensaj = $this->conexionObj2->consultar("SELECT nombre FROM mensajeros WHERE id_mensajero = '" . $row_select_lotes[6] . "'");
                $row_selectMensaj = mysql_fetch_array($rst_selectMensaj);
                $mensajero = $row_selectMensaj[0];
                echo "<td valign=top class=miTable_td>" . $mensajero . "</td>"; ##MENSAJERO
//					echo "<td valign=top class=miTable_td>".$row_select_lotes[7]."</td>";##SUCURSAL
                if ($perfil != 5) {
                    echo "<td valign=top class=miTable_td>";
                    ?>
                    <A HREF='accion_rastreo.php?tipo=1', onClick='window.open("accion_rastreo.php?guia=<? echo $row_select_lotes[0]; ?>&tipo=1&tabla=<? echo $tabla; ?>&id_suc=<? echo $suc; ?>", "window", "width=550,height=650,resizable=yes,scrollbars=yes");
                        return false'>Ver Rastreo</a>
                    <?
                    echo "</td>";
                }//fin del if del perfil
            }
        }

        function lista_guias_sc($inicio, $tamano_pagina, $suc, $user, $valor, $campo, $tabla) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $perfil = $_SESSION['perfil'];
            if ($perfil == 1) {
                $add = "WHERE g.$campo='" . $valor . "' ORDER BY g.orden DESC";
            } else {
                $add = "WHERE g.$campo='" . $valor . "' ORDER BY g.orden DESC"; //AND id_sucursal='".$suc."'
            }
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT g.guia, g.empresa, g.destinatario, g.direccion, g.telefono, g.ciudad " .
                    "FROM $tabla as g " .
                    "$add LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td2>";
                ?>
                <A HREF='accion_guia.php?tipo=1', onClick='window.open("accion_guia.php?guia=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=no");
                    return false'><? echo $row_select_lotes[0]; ?></a>
                <?
                echo "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[4] . "</td>";
                echo "<td valign=middle class=miTable_td><div align=center>" . $row_select_lotes[5] . "</div>";
                echo "</td>";
                echo "<td valign=top class=miTable_td2>";
                ?>
                <A HREF='accion_rastreo.php?tipo=1', onClick='window.open("accion_rastreo.php?guia=<? echo $row_select_lotes[0]; ?>&tipo=1&tabla=<? echo $tabla; ?>&id_suc=<? echo $suc; ?>", "window", "width=550,height=650,resizable=yes,scrollbars=yes");
                    return false'>Ver Rastreo</a>
                <?
                echo "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
            }
        }

        function lista_guias_clientes($inicio, $tamano_pagina, $suc, $user, $valor, $campo, $tabla, $id_cli, $tp_consulta, $add) {
            include("./logos.php");
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT g.guia, g.empresa, g.destinatario, g.direccion, g.telefono, g.ciudad,g.identificacion,g.especial1,
			   g.especial2,g.especial3,g.especial4,g.especial5,g.especial6,g.especial7,g.especial8,g.especial9,g.especial10,g.orden,e.nombre,g.path,g.no_paquete FROM $tabla as g inner join estados_gestion as e
			   on g.id_estado=e.id_estado $add LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {

                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>";
                $icono = "./imagenes/recursos/guia.gif";
                if (empty($row_select_lotes['path'])) {

                    $icono = "./imagenes/recursos/des_guia.gif";
                }
                ?>
                <A HREF='accion_guia.php?tipo=1', onClick='window.open("accion_guia.php?guia=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=no");
                    return false'><img src="<? echo $icono; ?>"></a>
                <?
                echo "</td>";





                echo "<td valign=top class=miTable_td>";
                ?>
                <A HREF='accion_rastreo.php?tipo=1', onClick='window.open("accion_rastreo.php?guia=<? echo $row_select_lotes[0]; ?>&tipo=1&tabla=<? echo $tabla; ?>&id_suc=<? echo $suc; ?>", "window", "width=550,height=650,resizable=yes,scrollbars=yes");
                    return false'>Ver Rastreo</a>
                <?
                echo "</td>";
                echo "<td valign=top class=miTable_td>";
                ?>
                <A HREF='accion_guia.php?tipo=1', onClick='window.open("accion_guia.php?guia=<? echo $row_select_lotes[0]; ?>&tabla=<? echo $tabla; ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=no");
                    return false'><? echo $row_select_lotes[0]; ?></a>
                <?
                echo "</td>";

                $f_entrega = '00-00-0000';
                if (!empty($row_select_lotes[11])) {
                    $f_entrega = date("d-m-Y", strtotime($row_select_lotes[11]));
                }
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[17] . "</td>"; ##Orden
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[18] . "</td>"; ##Estado
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>"; ##EMPRESA
                echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[2] . "</td>"; ##DESTINATARIO
                echo "<td valign=top class=miTable_td nowrap>" . $row_select_lotes[3] . "</td>"; ##DIRECCION
                echo "<td valign=top class=miTable_td>" . $f_entrega . "</td>"; ##ESPECIAL 5
                echo "<td valign=middle class=miTable_td><div align=center>" . $row_select_lotes[4] . "</div>"; ##TELEFONO
                echo "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[5] . "</td>"; ##CIUDAD
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[6] . "</td>"; ##IDENTIFICACION
                if (!empty($Tespecial1)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[7] . "</td>"; ##Especial1
                }
                if (!empty($Tespecial2)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[8] . "</td>"; ##Especial2
                }
                if (!empty($Tespecial3)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[9] . "</td>"; ##Especial3
                }
                if (!empty($Tespecial4)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[10] . "</td>"; ##Especial4
                }
                if (!empty($Tespecial6)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[12] . "</td>"; ##Especial4
                }
                if (!empty($Tespecial7)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[13] . "</td>"; ##Especial4
                }
                if (!empty($Tespecial8)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[14] . "</td>"; ##Especial4
                }
                if (!empty($Tespecial9)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[15] . "</td>"; ##Especial4
                }
                if (!empty($Tespecial10)) {
                    echo "<td valign=top class=miTable_td>" . $row_select_lotes[16] . "</td>"; ##Especial4
                }
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[20] . "</td>"; ##No Paquete
            }
        }

        function get_tabla($suc) {
            //$this->conexionObj2=new conexion();
            //$this->conexionObj2->conectarse();
            //$rst_select_tabla=$this->conexionObj2->consultar("SELECT nom_tabla FROM tablas_sucursales WHERE id_suc = '$suc'");
            //$row_select_tabla=mysql_fetch_array($rst_select_tabla);
            //$tabla=$row_select_tabla[0];
            $tabla = "guias_proceso";
            return $tabla;
        }

        function get_tabla_rastreo($suc) {
            //$this->conexionObj2=new conexion();
            //$this->conexionObj2->conectarse();
            //$rst_select_tabla=$this->conexionObj2->consultar("SELECT nom_rastreo FROM tablas_sucursales WHERE id_suc = '$suc'");
            //$row_select_tabla=mysql_fetch_array($rst_select_tabla);
            //$rastreo=$row_select_tabla[0];
            $rastreo = 'rastreo_guias';
            return $rastreo;
        }

        function get_tam($sql, $add) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $rst_tam = $this->conexionObj2->consultar("$sql $add");
            $row_tam = mysql_num_rows($rst_tam);
            return $row_tam;
        }

        function get_path() {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $rst_select_path = $this->conexionObj2->consultar("SELECT path FROM document_root");
            $row_select_path = mysql_fetch_array($rst_select_path);
            $path = $row_select_path[0];
            return $path;
        }

        function get_id($guia) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $rst_select_id = $this->conexionObj2->consultar("SELECT id FROM rastreo_guias WHERE guia = '$guia' ORDER BY id DESC");
            $row_select_id = mysql_fetch_array($rst_select_id);
            $id = $row_select_id[0];
            return $id;
        }

        function lista_planilla($inicio, $tamano_pagina, $suc, $user, $perfil, $planilla, $id_mens) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();

            if ($perfil == 1) {
                $add = '';
            } else {
                $add = " and  p.id_sucursal='$suc'";
            }
            if (!empty($planilla) and empty($id_mens))
                $add = $add . " and g.id_planilla='" . $planilla . "' ";
            if (!empty($id_mens) and empty($planilla))
                $add = $add . " and g.id_mensajero='" . $id_mens . "' ";
            if (!empty($id_mens) and !empty($planilla))
                $add = $add . " and g.id_mensajero='" . $id_mens . "' and g.id_planilla='" . $planilla . "'";
            $tabla = $this->get_tabla($suc);
            $rst_select_lotes = $this->conexionObj2->consultar("select g.id_planilla, p.fecha_planilla, p.hora_planilla, u.nombre as usuario, count(*) as con_guia, m.nombre as nom_men, p.id_mensajero
          from guias_proceso as g inner join planillas as p on (g.id_planilla=p.id_planilla)
                inner join mensajeros as m on (p.id_mensajero=m.id_mensajero)
	           left outer join usuarios as u on (p.id_usuario=u.id_usuario)
                where g.id_planilla<>0 $add group by  p.id_planilla
                order by p.id_planilla desc LIMIT $inicio,$tamano_pagina");


            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                $id_men = $row_select_lotes[6];
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td2><A HREF='ver_planilla.php?id_user=$user&suc=$suc&planilla=" . $row_select_lotes[0] . "&tabla=$tabla&id_men=$id_men'>" . $row_select_lotes[0] . "</A></td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[4] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[5] . "</td>";
            }
        }

        function lista_manifiesto($inicio, $tamano_pagina, $suc, $user, $perfil) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            if ($perfil == 1) {
                $add = '';
            } else {
                $add = "WHERE p.id_sucursal_orig='$suc'";
            }
            $tabla = $this->get_tabla($suc);
            $rst_select_lotes = $this->conexionObj2->consultar("SELECT p.id_manifiesto, p.fecha_manifiesto, p.hora_manifiesto, u.nombre, p.cantidad, m.nombre FROM manifiesto as p inner join sucursales as m on p.id_sucursal_dest=m.id_sucursal inner join usuarios as u on p.id_usuario=u.id_usuario $add order by id_manifiesto DESC LIMIT $inicio,$tamano_pagina");
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td2><A HREF='ver_manifiesto.php?id_user=$user&suc=$suc&manifiesto=" . $row_select_lotes[0] . "&tabla=$tabla'>" . $row_select_lotes[0] . "</A></td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[4] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes[5] . "</td>";
            }
        }

        function cuenta_ods($inicio, $tamano_pagina, $user, $suc, $perfil) {
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $id_cli = $_SESSION['cliente'];
            if ($perfil == 5) {
                $add = " WHERE id_sucursal='" . $suc . "' AND id_cliente='" . $id_cli . "'";
            } else {
                $add = '';
            }

            $tabla = "guias_proceso";
$cons_orden='';
$zona_ordenes_='';
if($_SESSION['area']!='0'){
if($_SESSION['zona']!='0'){$zona_ordenes_=" and gp.cod_zona='".$_SESSION['zona']."' ";}

$cons_orden="select producto,fecha_creacion,gp.orden,count(*) as total_ from (
select producto,fecha_creacion,orden from ordenes o 
where o.tp_digita=1 and 
o.fecha_creacion BETWEEN date_sub(curdate(), interval 4 month)  AND curdate() 
ORDER BY Id DESC) a
inner join guias_proceso gp
on a.orden = gp.orden
where gp.especial2 in (".$_SESSION['area'].")".$zona_ordenes_."
group by gp.orden order by gp.fecha_cargue desc limit " . $inicio . "," . $tamano_pagina;

}else{
$cons_orden = "select producto,fecha_creacion,orden,space(25) as total from ordenes " . $add . " order by fecha_creacion desc limit " . $inicio . "," . $tamano_pagina;}
//echo $cons_orden;

//$cons_orden = "select producto,fecha_creacion,orden,space(25) as total from ordenes " . $add . " order by fecha_creacion desc limit " . $inicio . "," . $tamano_pagina;


            $rst_select_lotes = $this->conexionObj2->consultar($cons_orden);
            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                $v_orden = $row_select_lotes['orden'];
                $cnt_orden = $this->conexionObj2->consultar("select count(*) as total from guias_proceso where orden='" . $v_orden . "'");
                $v_total = mysql_fetch_array($cnt_orden);
                $cnt_total = $v_total['total'];
                $row_select_lotes['total'] = $cnt_total;
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td2><A HREF='ejecuta_rastreo.php?id_user=$user&suc=$suc&ods=" . $row_select_lotes['orden'] . "&tabla=$tabla'>" . $row_select_lotes['orden'] . "</A></td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['producto'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['fecha_creacion'] . "</td>";

if($_SESSION['area']!='0'){
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['total_'] . "</td>";
}else{
		echo "<td valign=top class=miTable_td>" . $row_select_lotes['total'] . "</td>";
}
            }
        }

    }

    class select_ciudades {

        var $conexionObj2;

        function ciudad($inicio, $tamano_pagina, $add) {
            $i = 0;
            $this->conexionObj2 = new conexion();
            $this->conexionObj2->conectarse();
            $rst_select_lotes = $this->conexionObj2->consultar("(SELECT c.id_ciudad, c.nombre, c.id_depto, d.nombre as nom_d FROM ciudades as c " .
                    " join departamentos as d on (c.id_depto=d.cod_depto)  $add ) ORDER BY nombre LIMIT $inicio,$tamano_pagina");

            while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
                $i++;
                echo "<tr class=miTable_tr>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['0'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['1'] . "</td>";
                echo "<td valign=top class=miTable_td>" . $row_select_lotes['3'] . "</td>";
                echo "<td valign=middle class=miTable_td>";
                ?>
                <a href='accion_ciudad.php?id_ciudad=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=1' onClick="window.open('accion_ciudad.php?id_ciudad=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=1&nombre=<? echo "" . $row_select_lotes['1'] . ""; ?>&depto=<? echo "" . $row_select_lotes['2'] . ""; ?>&zona=<? echo "" . $row_select_lotes['3'] . ""; ?>', 'window', 'width=300,height=200');
                    return false">
                    <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td>
                <a href='accion_ciudad.php?id_ciudad=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=2' onClick="window.open('accion_ciudad.php?id_ciudad=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=2&nombre=<? echo "" . $row_select_lotes['1'] . ""; ?>&depto=<? echo "" . $row_select_lotes['2'] . ""; ?>&zona=<? echo "" . $row_select_lotes['3'] . ""; ?>', 'window', 'width=300,height=200');
                    return false">
                    <img src='imagenes/del.gif'></a><?
            echo "<input type=checkbox id='del_ciu' name='del_ciu[$i]' value=" . $row_select_lotes['0'] . " class=inputbox ></td>";
        }
    }

}

class select_departamentos {

    var $conexionObj2;

    function dptos($inicio, $tamano_pagina, $add) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        if ($add) {
            $add1 = "WHERE " . $add;
            $add2 = "AND " . $add;
        }
        $rst_select_lotes = $this->conexionObj2->consultar("select id_depto, cod_depto, nombre from departamentos $add ORDER BY nombre LIMIT $inicio,$tamano_pagina");
        $rst_select_lotes2 = "select id_depto, cod_depto, nombre from departamentos $add ORDER BY nombre LIMIT $inicio,$tamano_pagina";
        echo "<br>";
        while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
            echo "<tr class=miTable_tr>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['0'] . "</td>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['1'] . "</td>";
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['2'] . "</td>";
            echo "<td valign=middle class=miTable_td>";
            ?>
                <a href='accion_depto.php?id_depto=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=1' onClick="window.open('accion_depto.php?id_depto=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=1&nombre=<? echo "" . $row_select_lotes['2'] . ""; ?>&cod_depto=<? echo "" . $row_select_lotes['1'] . ""; ?>', 'window', 'width=300,height=200');
                    return false">
                    <center><img src='imagenes/reload_.gif'></center></a></td>
            <td valign=middle class=miTable_td width="50">
                <a href='accion_depto.php?id_depto=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=2' onClick="window.open('accion_depto.php?id_depto=<? echo "" . $row_select_lotes['0'] . ""; ?>&tipo=2&nombre=<? echo "" . $row_select_lotes['2'] . ""; ?>&cod_depto=<? echo "" . $row_select_lotes['1'] . ""; ?>', 'window', 'width=300,height=200');
                    return false">
                    <img src='imagenes/del.gif'></a><?
            echo "<input type=checkbox id='del_dpto' name='del_dpto[$i]' value=" . $row_select_lotes['0'] . " class=inputbox ></td>";
        }
    }

}

##FUNCIONES DIEGO.##

function ConsultaPlanilla($id_mensajero) {
    $sql = "select id_planilla from planillas where fecha_planilla=date(now()) and id_mensajero='" . $id_mensajero . "'";
    $rs = mysql_query($sql, $GLOBALS["v_mysql"]) or die("Error MySql: " . mysql_error() . " Linea: 2372 - FuncionesBK.");
    $cnt = mysql_num_rows($rs);
    if ($cnt > 0) {
        $MyArr = @mysql_fetch_array($rs);
        $id_pla = $MyArr[0];
    } else {
        $id_pla = '0';
    }
    return $id_pla;
}

class consultas_mysql {

    var $conexionObj2;

    function detalle_guias($inicio, $tamano_pagina, $user, $suc, $f1, $f2, $nestado, $_add) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $i = 0;
        $perfil = $_SESSION['perfil'];
        $suc;
        if ($perfil == 1) {
            $add = "WHERE t.id_estado in $nestado and fecha_cargue between '$f1' and '$f2' " . $_add;
        } else {
            $add = "WHERE t.id_sucursal='$suc' and t.id_estado in $nestado and t.fecha_cargue between '$f1' and '$f2' " . $_add;
        }
        $_sql = "select t.guia,t.empresa,t.destinatario,t.direccion,t.telefono,t.ciudad,t.identificacion,t.orden,t.especial1,t.especial2,t.especial3,
			   t.especial4,t.especial5,concat(fecha_cargue,' ',hora_cargue) as fec_ini,space(25) as tiempo,b.producto from guias_proceso as t 
			   inner join ordenes as b on t.orden=b.orden 
			 		" . $add . " limit " . $inicio . "," . $tamano_pagina;
        $rst_select_lotes = $this->conexionObj2->consultar($_sql);
        echo mysql_error();
        while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
            $i++;
            echo "<tr class=miTable_tr>";
            echo "<td valign=top class=miTable_td>";
            ?>
                <A HREF="accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0]; ?>", onClick='window.open("accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0] ?>&prod=<? echo $row_select_lotes[6] ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=yes");
                    return false'><? echo $row_select_lotes[0]; ?></A></td>
            <?
            $f_entrega = '00-00-0000';
            if (!empty($row_select_lotes[12]) and $row_select_lotes[12] != '0000-00-00') {
                $f_entrega = date("d-m-Y hh:mm:ss", strtotime($row_select_lotes[12]));
            }
            $retor = calcula_tiempo($row_select_lotes[13], $row_select_lotes[12]);
            $row_select_lotes[14] = $retor;
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[7] . "</td>"; ##ORDEN
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[15] . "</td>"; ##PRODUCTO
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[1] . "</td>"; ##EMPRESA					
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[2] . "</td>"; ##DESTINATARIO
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[3] . "</td>"; ##DIRECCION
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[13] . "</td>"; ##Fecha Cargue.
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[12] . "</td>"; ##Fecha Entrega
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[14] . "</td>"; ##Tiempo Calculado.
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[4] . "</td>"; ##TELEFONO
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[5] . "</td>"; ##CIUDAD
            echo "<td valign=top class=miTable_td>" . $row_select_lotes[6] . "</td>"; ##IDENTIFICACION
        }
    }

    function registros_devolucion_fecha($inicio, $tamano_pagina, $user, $suc, $tabla, $fec1, $fec2, $bandera) {
        include("./logos.php");
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        $i = 0;
        $perfil = $_SESSION['perfil'];

        if ($bandera == 1) {

            if ($perfil == 1) {
                $add = "WHERE t.id_estado = '16' AND t.id_devolucion > '0' and (date(fecha_cargue) BETWEEN '$fec1' and '$fec2')";
            } else {
                $add = "WHERE t.id_sucursal='$suc' AND t.id_estado = '16' AND t.id_devolucion > '0' and (date(fecha_cargue) BETWEEN '$fec1' and '$fec2')";
            }
        } else {

            if ($perfil == 1) {
                $add = "WHERE t.id_estado = '16' AND t.id_devolucion > '0' and (date(o.f16) BETWEEN '$fec1' and '$fec2')";
            } else {
                $add = "WHERE t.id_sucursal='$suc' AND t.id_estado = '16' AND t.id_devolucion > '0' and (date(o.f16) BETWEEN '$fec1' and '$fec2')";
            }
        }

        $rst_select_lotes = $this->conexionObj2->consultar("SELECT t.guia, t.fecha_cargue, t.destinatario, t.direccion, t.telefono, t.ciudad, t.identificacion,t.orden,
			  c.nombre ,o.f16,m.nombre as mensajero " .
                " FROM guias_proceso as t inner join rastreo_guias as o on t.guia=o.guia inner join devoluciones as c on t.id_devolucion=c.id_devolucion" .
                " inner join mensajeros as m on t.id_mensajero=m.id_mensajero $add LIMIT $inicio,$tamano_pagina");
        echo mysql_error();
        while ($row_select_lotes = mysql_fetch_array($rst_select_lotes)) {
            $i++;
            echo "<tr class=miTable_tr>";
            echo "<td valign=top class=miTable_td>";
            ?>
            <A HREF="accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0]; ?>", onClick='window.open("accion_guia.php?tabla=<? echo $tabla; ?>&guia=<? echo $row_select_lotes[0] ?>&prod=<? echo $row_select_lotes[6] ?>", "window", "width=650,height=600,toolbars=no,scrollbars=yes,resizable=yes");
                    return false'><? echo $row_select_lotes[0]; ?></A></td>
    
                    <td valign=top class=miTable_td>
                    <A HREF='accion_rastreo.php?tipo=1', onClick='window.open("accion_rastreo.php?guia=<? echo $row_select_lotes[0]; ?>&tipo=1&tabla=<? echo $tabla; ?>&id_suc=<? echo $suc; ?>", "window", "width=550,height=650,resizable=yes,scrollbars=yes");
                     return false'>Ver Rastreo</a>
                    </td>        
            <?
            $f_entrega = '00-00-0000';
            if (!empty($row_select_lotes[13])) {
                $f_entrega = date("d-m-Y", strtotime($row_select_lotes[13]));
            }
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['orden'] . "</td>"; ##ORDEN
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['fecha_cargue'] . "</td>"; ##FECHA CARGUE
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['destinatario'] . "</td>"; ##DESTINATARIO
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['direccion'] . "</td>"; ##DIRECCION
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['mensajero'] . "</td>"; ##MENSAJERO
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['f16'] . "</td>"; ##FECHA DEVOLUCION
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['nombre'] . "</td>"; ##MOTIVO DEVOLUCION
            echo "<td valign=top class=miTable_td>" . $row_select_lotes['ciudad'] . "</td>"; ##CIUDAD					

//            if (!empty($Tespecial1)) {
//                echo "<td valign=top class=miTable_td>" . $row_select_lotes[9] . "</td>"; ##Especial1
//            }
//            if (!empty($Tespecial2)) {
//                echo "<td valign=top class=miTable_td>" . $row_select_lotes[10] . "</td>"; ##Especial2
//            }
//            if (!empty($Tespecial3)) {
//                echo "<td valign=top class=miTable_td>" . $row_select_lotes[11] . "</td>"; ##Especial3
//            }
//            if (!empty($Tespecial4)) {
//                echo "<td valign=top class=miTable_td>" . $row_select_lotes[12] . "</td>"; ##Especial4
//            }

            echo "<td valign=top class=miTable_td>";
            echo "</td>";
        }
    }

}

function convert_datetime($str) {

    list($date, $time) = explode(' ', $str);
    list($year, $month, $day) = explode('-', $date);
    list($hour, $minute, $second) = explode(':', $time);

    $timestamp = mktime($hour, $minute, $second, $month, $day, $year);

    return $timestamp;
}

function calcula_tiempo($ttIni, $ttFin) {
    if ($ttFin == '0000-00-00 00:00:00') {
        $ttFin = date("Y-m-d H:i:s");
    }

    if (empty($ttFin)) {
        $ttFin = date("Y-m-d H:i:s");
    }

    $ttIni = convert_datetime($ttIni);
    $ttFin = convert_datetime($ttFin);
    $diferencia = $ttFin - $ttIni;
    $r_segundos = $diferencia % 60;
    $minutos = ($diferencia - $r_segundos) / 60;
    $r_minutos = $minutos % 60;
    $horas = ($minutos - $r_minutos) / 60;
    $r_horas = $horas % 24;
    $dias = ($horas - $r_horas) / 24;

    if ($dias > 0) {
        $var_retor = $dias . " Dia(s) " . $r_horas . " Hora(s) " . $r_minutos . " Minuto(s) ";
    } else {
        if ($horas > 0) {
            $var_retor = $horas . " Hora(s) " . $r_minutos . " Minuto(s) ";
        } else {
            if ($minutos > 0) {
                $var_retor = $minutos . " Minuto(s) ";
            } else {
                $var_retor = $segundos . " Segundo ";
            }
        }
    }
    Return $var_retor;
}

function EncabezadoSinMenu($target) {
    if (!empty($target))
        $onload = "onload='javascript:document.backup." . $target . ".focus()'";

    echo"<html>";
    echo"<head>";
    echo"<title>.:: WEBSIM GAMMA ::.</title>";
    echo"<meta name=\"author\" content='DESARROLLO WEB'>";
    echo"<link rel='stylesheet' href='css/style.css' type=\"text/css\">";
    echo"<link rel=\"SHORTCUT ICON\" href=imagenes/icon_gamma.gif>";
    echo"</head>";
    echo"<body " . $onload . " leftmargin=\"0\" topmargin=\"0\" marginheight=\"0\" marginwidth=\"0\" bgcolor=\"#ffffff\" >";
    ?>
    <center><table width="1004" height="101" border="0" cellpadding="0" cellspacing="0">
            <tbody><tr>
                    <td background="imagenes/baner.jpg"></td>
                </tr>
            </tbody></table></center></div>
    <br>
    <?php
//    echo"<center>";
//    echo"<center><table border=0 width=1004 cellspacing=0>";
//    echo"<tr>";
//    echo"<td width=21% background=\"imagenes/bg2.jpg\" valign=top class='titulo'>Usuario: " . $_SESSION['nombre_usuario'];
//    echo "<br>Perfil: " . $_SESSION['perfil_usuario'];
//    if ($_SESSION['perfil'] == '5') {
//        echo "<br>Cliente: " . $_SESSION['nombre_cliente'];
//    }
//    echo "<br>Fecha: " . $Fecha . " Hora:" . $Hora;
}
?>

