<?php
if(isset($_POST["bexp"])) {	
	$varFIni = ($_POST["eini"]=="") ? "NULL" : "'".FechaMySql($_POST["eini"])."'";
	$varFFin = ($_POST["efin"]=="") ? "NULL" : "'".FechaMySql($_POST["efin"])."'";
	$varProv = ($_POST["pcod"]=="") ? "NULL" : $_POST["pcod"];		
	$sql = "call spQuery_Registro_Compras($varProv, $varFIni, $varFFin);";
	$_SESSION[expor_sql_1] =  $sql;
	$_SESSION[expor_sql_2] = NULL;
	$dir = "export.php?page=".$_POST["titu"];
	header("location: $dir");
	}
require_once('clases/xajax/xajax_core/xajax.inc.php');
$xajax = new xajax();
//$xajax->setFlag('debug',true); 
$xajax->configure('javascript URI', 'clases/xajax/');

require "clases/KoolAjax/koolajax.php";
$koolajax->scriptFolder = "clases/KoolAjax";
	
function seleccionaProducto($ide) {
	if($ide<>"") {
		$var = VarServer("MYSQLI");
		$obj = new clsConexion($var[0],$var[1],$var[2],$var[3],$var[4]);
		$obj->AbrirConexion();
		$sql = "call spQuery_Lista_Producto('$ide','');";
		$rs = $obj->Query($sql);
		$obj->CerrarConexion();
		$Fila = $obj->FetchArray($rs);
		if($obj->NumFilas($rs)>0) $retorna = $Fila["PRODUCTO"]."[[sep]]".$Fila["UM_COMPRA"]."[[sep]]".$Fila["PRECIO_COMPRA"];
		else $retorna = "NO EXISTE";
		}
	return $retorna;
	}

function seleccionar_proveedor($ide) {
	if($ide<>"") {
		$var = VarServer("MYSQLI");
		$obj = new clsConexion($var[0],$var[1],$var[2],$var[3],$var[4]);
		$obj->AbrirConexion();
		$sql = "call spQuery_Lista_Proveedor('$ide','');";
		$rs = $obj->Query($sql);
		$obj->CerrarConexion();
		$Fila = $obj->FetchArray($rs);
		if($obj->NumFilas($rs)>0) $retorna = utf8_encode($Fila[1]);
		else $retorna = "NO EXISTE";		
		}
	else $retorna = "";
	
	$objResponse = new xajaxResponse();
	$objResponse->assign("pnom", "value", $retorna);
	return $objResponse;		
	}
	
function fn_redirect($varLink  = NULL, //Direccion para redireccionar		
					 $varOpcio = NULL, //Variable Opcion
					 $varParam = NULL, //Nombre Variable Adicional
					 $varValor = NULL  //Valor de Variable Adicional
					 ) {
	if(isset($varLink) && $varLink<>"") {
		$varRut = $varLink;
		$varOpt = (isset($varOpcio) && $varOpcio<>"")?"opt=".$varOpcio:NULL;
		$varPar = (isset($varParam) && $varParam<>"")?$varParam."=":NULL;
		$varPar.= (isset($varValor) && $varValor<>"" && $varPar<>"")?$varValor:NULL;
		
		if(isset($varOpt) && $varOpt<>"") {
			$varRut.= (isset($varPar) && $varPar<>"")?"?".$varOpt."&".$varPar:"?".$varOpt;
			}
		else {
			$varRut.= (isset($varPar) && $varPar<>"")?"?".$varPar:NULL;
			}
		$objResponse = new xajaxResponse();	
		$objResponse->redirect($varRut);
		return $objResponse;
		}
	}
$xajax->register(XAJAX_FUNCTION, 'seleccionar_proveedor');
$xajax->register(XAJAX_FUNCTION, 'fn_redirect');
$xajax->processRequest();
$xajax->printJavascript("clases/xajax");
$koolajax->enableFunction("seleccionaProducto");
echo $koolajax->Render();
?>
<script language="javascript">
function CalcularItem(i) {
	var varCant = 0;
	var varUnitario = 0;
	var varDes  = 0;
	
	var vuni = document.getElementById('ipre['+i+']');
	var vcan = document.getElementById('ican['+i+']');
	var vdes1 = document.getElementById('ides1['+i+']');
	var vdes2 = document.getElementById('ides2['+i+']');
	var vtot = document.getElementById('itot['+i+']');
	
	if (vuni.value=="") varUnitario = "0";
	else	varUnitario = vuni.value;
	
	if (vcan.value=="") varCant	="0";
	else	varCant = vcan.value;
	
	if (vdes1.value=="") varDes1	="0";
	else	varDes1 = vdes1.value;
	
	if (vdes2.value=="") varDes2	="0";
	else	varDes2 = vdes2.value;
	
	var varTotTemp = parseFloat(varUnitario)*parseFloat(varCant);
	var varTotal1  = parseFloat(varTotTemp) - parseFloat(varTotTemp)*parseFloat(varDes1)/100;
	var varTotal2  = parseFloat(varTotal1) - parseFloat(varTotal1)*parseFloat(varDes2)/100;
	
	vtot.value = redondear(varTotal2,2);
	CalculaRTotal();
	}

function CalcularItemSubTotal(i) {
	var varCant = 0;
	var varUnitario = 0;
	var varDes1 = 0;
	var varDes2 = 0;
	var varTot	= 0;
	
	var vuni  = document.getElementById('ipre['+i+']');
	var vcan  = document.getElementById('ican['+i+']');
	var vdes1 = document.getElementById('ides1['+i+']');
	var vdes2 = document.getElementById('ides2['+i+']');
	var vtot  = document.getElementById('itot['+i+']');
	
	if (vuni.value=="") varUnitario = "0";
	else	varUnitario = vuni.value;
	
	if (vcan.value=="") varCant	= "0";
	else	varCant = vcan.value;
	
	if (vdes1.value=="") varDes1	= "0";
	else	varDes1 = vdes1.value;
	
	if (vdes2.value=="") varDes2	= "0";
	else	varDes2 = vdes2.value;
	
	if (vtot.value=="") varTot	= "0";
	else	varTot = vtot.value;
	
	var varDesTot = 1 - (1 - varDes1/100)*(1 - varDes2/100);
	varUnitario  = (parseFloat(varTot)/(1 - varDesTot))/parseFloat(varCant);
	vuni.value = redondear(varUnitario,5);
	CalculaRTotal();
	}
		
function CalculaRTotal() {
	var form = document.getElementById('form');
	var sto = 0;
	for (i=0;i<form.elements.length;i++) {	
		var Campo = form.elements[i].name;		
		if(Campo.indexOf("itot")==0) {			
			if (form.elements[i].value!="") {				
				sto = sto + parseFloat(form.elements[i].value);		
				}
			}
		}
	var vTot = document.getElementById('tot');
	var vSub = document.getElementById('stot');
	var vIgv = document.getElementById('igv');
	var vFla = document.getElementById('flag_igv');
	if (vFla.value == "S") {
		vTot.value = redondear(sto,2);
		vIgv.value = redondear(sto-sto/1.18,2);
		vSub.value = redondear(sto/1.18,2);
		}
	else {
		vSub.value = redondear(sto,2);
		vIgv.value = redondear(sto*0.18,2);
		vTot.value = redondear(sto*1.18,2);
		}
	}
	
function restar() {
    var miTabla = document.getElementById("cuerpoTabla");
    var i = 0;
    do
        if (miTabla.rows[i].getElementsByTagName("input")[0].checked == true)
            miTabla.deleteRow(i);
        else
            i ++;
    while (miTabla.rows.length != i)
}

function suma()  {
	var vnum = document.getElementById('num');
	var num = parseInt(vnum.value)+1;
	var miTabla = document.getElementById("cuerpoTabla");
	var fila = document.createElement("tr");
	var celda1 = document.createElement("td");
	var celda2 = document.createElement("td");
	var celda3 = document.createElement("td");
	var celda4 = document.createElement("td");
	var celda5 = document.createElement("td");
	var celda6 = document.createElement("td");
	var celda7 = document.createElement("td");
	var celda8 = document.createElement("td");
	var celda9 = document.createElement("td");
	
	fila.setAttribute("bgcolor","#F5FAFA");
	fila.setAttribute("onMouseOver","uno(this,'#FFFF33')");
	fila.setAttribute("onMouseOut","dos(this,'#F5FAFA')");
	celda1.setAttribute("align","center");	
	celda1.setAttribute("class","interior");
	celda2.setAttribute("class","interior");
	celda3.setAttribute("class","interior");
	celda4.setAttribute("align","center");
	celda4.setAttribute("class","interior");
	celda5.setAttribute("align","center");
	celda5.setAttribute("class","interior");
	celda6.setAttribute("align","center");
	celda6.setAttribute("class","interior");
	celda7.setAttribute("align","center");
	celda7.setAttribute("class","interior");
	celda8.setAttribute("align","center");
	celda8.setAttribute("class","interior");
	celda9.setAttribute("align","center");
	celda9.setAttribute("class","interior");
		
	celda1.innerHTML = "<input id='icod["+num+"]' name='icod["+num+"]'  autocomplete='off' type='text' style='text-align:center; width:80px' ondblclick=\"fn_cargar_listado_producto_compra('icod["+num+"]', 'inom["+num+"]', 'iuni["+num+"]', 'ipre["+num+"]')\" onkeypress=\"return SoloEnteros(event)\" onblur=\"select_producto('icod["+num+"]', 'inom["+num+"]', 'iuni["+num+"]', 'ipre["+num+"]')\" tabindex=\""+num+"\"/>";		
	celda2.innerHTML = "<input id='inom["+num+"]' name='inom["+num+"]' type='text' class='inputDisable' readonly style='width:350px' />";
	celda3.innerHTML = "<input id='iuni["+num+"]' name='iuni["+num+"]' type='text' class='inputDisable' readonly style='text-align:center; width:50px' />";
	celda4.innerHTML = "<input id='ipre["+num+"]' name='ipre["+num+"]'  autocomplete='off' type='text' onkeypress=\"return SoloNumeros(event)\" onkeyup=\"CalcularItem('"+num+"')\" style='text-align:right;width:60px' tabindex=\""+num+"\"/>";	
	celda5.innerHTML = "<input id='ican["+num+"]' name='ican["+num+"]' autocomplete='off' type='text' onkeypress=\"return SoloNumeros(event)\" onkeyup=\"CalcularItem('"+num+"')\" style='text-align:right;width:50px' tabindex=\""+num+"\"/>";
	celda6.innerHTML = "<input id='ides1["+num+"]' name='ides1["+num+"]'  autocomplete='off' type='text' onkeypress=\"return SoloNumeros(event)\" onkeyup=\"CalcularItem('"+num+"')\" style='text-align:right;width:40px' tabindex=\""+num+"\" value=\"0\" />";
	celda7.innerHTML = "<input id='ides2["+num+"]' name='ides2["+num+"]'  autocomplete='off' type='text' onkeypress=\"return SoloNumeros(event)\" onkeyup=\"CalcularItem('"+num+"')\" style='text-align:right;width:40px' tabindex=\""+num+"\" value=\"0\" />";
	celda8.innerHTML = "<input id='itot["+num+"]' name='itot["+num+"]'  autocomplete='off' type='text' onkeypress=\"return SoloNumeros(event)\" onkeyup=\"CalcularItemSubTotal('"+num+"')\"  tabindex=\""+num+"\" style='text-align:right;width:60px'/>";		
	celda9.innerHTML = "<a hre='#' onClick='DeleteRow(this)'> <img src='images/b_drop.png' border='0'></a>";
	fila.appendChild(celda1);
	fila.appendChild(celda2);
	fila.appendChild(celda3);
	fila.appendChild(celda4);
	fila.appendChild(celda5);
	fila.appendChild(celda6);
	fila.appendChild(celda7);
	fila.appendChild(celda8);
	fila.appendChild(celda9);
	miTabla.appendChild(fila);
	vnum.value=num;
	}

function DeleteRow(x) {
	while (x.tagName.toLowerCase() !='tr') {
		if(x.parentElement)
			x=x.parentElement;
		else if(x.parentNode)
			x=x.parentNode;
		else
		return;
		}
	var rowNum=x.rowIndex;
	while (x.tagName.toLowerCase() !='table') {
		if(x.parentElement)
			x=x.parentElement;
		else if(x.parentNode)
			x=x.parentNode;
		else
			return;
		}
	x.deleteRow(rowNum);
	CalculaTotal();
	}
	
function valida(e){
	tecla=(document.all) ? e.keyCode : e.which;
	if(tecla == 13)
	document.form.cond.focus();
	}
	
function pulsar(e, a) {
	tecla=(document.all) ? e.keyCode : e.which;
	var Campo = a.name;		
		
	if(tecla==13) {
		if(Campo == "ccod") {
			cargar("U","C",a.value,document.form.emp.value);
			document.form.cond.focus();
			}
		if(Campo.indexOf("acod")==0) {
			msj_articulo = "NO PRESIONES ENTER\n";
			}
		}
	return(tecla!=13);
//	document.form.cond.focus();
	}



		
function select_producto(ccod, cnom, cum, cuni) {
	var ccod1 = document.getElementById(ccod);
	var cnom1 = document.getElementById(cnom);
	var cum1  = document.getElementById(cum);
	var cuni1 = document.getElementById(cuni);
	var existe="NO";
	var form = document.getElementById('form');	
	if(ccod1.value=="") {
		ccod1.value = "";
		cnom1.value = "";
		//cum1.value  = "";
		cuni1.value = "";
		}
	else {		
		var dato = koolajax.callback(seleccionaProducto(ccod1.value));
		if(dato=="NO EXISTE") {
			alert("PRODUCTO ESCRITO NO EXISTE...");
			ccod1.value = "";
			cnom1.value = dato;
			cum1.value  = "";
			//cuni1.value = "";
			ccod1.focus();
			}
		else {
			var myArray = dato.split('[[sep]]');
			for (i=0;i<form.elements.length;i++) {
				var Campo = form.elements[i].name;					 	
				if(Campo.indexOf("icod")==0 && form.elements[i].value==ccod1.value && Campo != ccod) {
					existe="SI";	
					}	
				}
				
			if (existe=="SI") {
				ccod1.value = "";
				cnom1.value = "";
				cum1.value = "";
				//cuni1.value = "";
				alert("EL ARTICULO : " + ccod1.value + "\n" + myArray[0] + "\nYA ESTA AGREGADO, SELECCIONE OTRO POR FAVOR");
				ccod1.focus();
				}
			else {
				cnom1.value = myArray[0];
				cum1.value  = myArray[1];
				//cuni1.value = myArray[2];
				}
			}
		}
	}
</script>
<?php

function MyTable($obj, $Titulo, $Opcion, $Valor) {
	$Link = $_SERVER['PHP_SELF'];
	$varFINI = (isset($_POST["eini"]))?$_POST["eini"]:NULL;
	$varFFIN = (isset($_POST["efin"]))?$_POST["efin"]:NULL;
	$varPCOD = (isset($_POST["pcod"]))?$_POST["pcod"]:NULL;
	$varPNOM = (isset($_POST["pnom"]))?$_POST["pnom"]:NULL;
	if(!isset($Opcion)) {
		$varTabla=array("id"=>"tabla", "name"=>"table", "tamano"=>"420", "clase"=>"Formtitulo", "titulo"=>$Titulo." - BUSQUEDA",
						"formu"=>array("id"=>"form", "name"=>"form", "metodo"=>"POST"),						
						"ocult"=>array(array("tipo"=>"oculto", "id"=>"titu", "name"=>"titu", "valor"=>$Titulo),
									   array("tipo"=>"oculto", "id"=>"opt", "name"=>"opt", "valor"=>$Opcion)
									  ),
						"conte"=>array(array("titulo"=>"Proveedor :", "clase1"=>"FormCampo1", "clase2"=>"interior",
										     "campo"=>array("tipo"=>"varios",
														    "contenido"=>array(array("tipo"=>"text", "id"=>"pcod", "name"=>"pcod", "valor"=>$varPCOD, 
																					 "ancho"=>"60",  "alinear"=>"center", 
																					 "blur"=>"xajax_seleccionar_proveedor(this.value)", 
																					 "dclick"=>"fn_cargar_listado_proveedor('pcod', 'pnom')"),
																			   array("tipo"=>"text", "id"=>"pnom", "name"=>"pnom", "valor"=>$varPNOM, 
																			   		 "ancho"=>"220", "clase"=>"inputDisable", "locked"=>"SI")
																			   )
														 )
										  	 ),									  							  
									   array("titulo"=>"Fecha Incial :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
											 "campo"=>array("tipo"=>"fecha", "id"=>"eini", "name"=>"eini", "alinear"=>"center","valor"=>$varFINI) ),
									   array("titulo"=>"Fecha Final :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
											 "campo"=>array("tipo"=>"fecha", "id"=>"efin", "name"=>"efin", "alinear"=>"center", "valor"=>$varFFIN) )									   
									   ),
						"boton"=>array(array("tipo"=>"submit", "id"=>"bcon", "name"=>"bcon", "ancho"=>"100", "alto"=>"22", "texto"=>"Consultar"),			  
									   array("tipo"=>"submit", "id"=>"bexp", "name"=>"bexp", "ancho"=>"100", "alto"=>"22", "texto"=>"Exportar"),
									   array("tipo"=>"submit", "id"=>"bnew", "name"=>"bnew", "ancho"=>"100", "alto"=>"22", 
											 "texto"=>"Nueva Compra", "click"=>"xajax_fn_redirect('".$Link."','NEW'); return false;"),									)
						);
		echo $obj->setTablaForm($varTabla);
	
		if(isset($_POST["bcon"])) {		
			$varFIni = ($_POST["eini"]=="") ? "NULL" : "'".FechaMySql($_POST["eini"])."'";
			$varFFin = ($_POST["efin"]=="") ? "NULL" : "'".FechaMySql($_POST["efin"])."'";
			$varProv = ($_POST["pcod"]=="") ? "NULL" : $_POST["pcod"];		
			$sql = "call spQuery_Registro_Compras_Update($varProv, $varFIni, $varFFin);";

			$varTabla=array("id"=>"theTable", "name"=>"theTable", "tamano"=>"1000", "sql_cab"=>$sql, "pages"=>50,
							"conte"=>array(array("tamano"=>20, "titulo"=>"IDE", "alinear"=>"center"),
										   array("tamano"=>50, "titulo"=>"EMISION", "alinear"=>"center", "clase"=>"sortable-date-dmy"),
										   array("tamano"=>10, "titulo"=>"CTIP", "alinear"=>"center", "oculto"=>"SI"),
										   array("tamano"=>50, "titulo"=>"TIPO DOC"),
										   array("tamano"=>90, "titulo"=>"DOCUMENTO"),
										   array("tamano"=>40, "titulo"=>"EST.", "alinear"=>"center"),										   
										   array("tamano"=>10, "titulo"=>"CPRO", "alinear"=>"center"),
										   array("tamano"=>250,"titulo"=>"PROVEEDOR", "funcion"=>array("contar")),
										   array("tamano"=>60, "titulo"=>"SUBTOTAL", "alinear"=>"right"),
										   array("tamano"=>60, "titulo"=>"IGV", "alinear"=>"right"),
										   array("tamano"=>60, "titulo"=>"TOTAL", "alinear"=>"right"),
										   array("tamano"=>120, "titulo"=>"FECHA CREADO", "alinear"=>"center"),
										   array("tamano"=>100, "titulo"=>"MODIFI", "alinear"=>"center", "oculto"=>"SI"),
										   array("tamano"=>100, "titulo"=>"USUARIO", "alinear"=>"center"),
										   array("tamano"=>100, "titulo"=>"MODIFI", "alinear"=>"center", "oculto"=>"SI")
										   ),
							"boton"=>array(array("tipo"=>"img", "id"=>"bdet", "name"=>"bdet", "img"=>"images/b_table_edit.png", 
										   		 "toltip"=>array(array("valor"=>"HAGA CLICK PARA <b>VER EL DETALLE</b> DE LA COMPRA<br><b>Fecha Emisión : </b>"),
																 array("valor"=>1, "tipo"=>"INDEX"),
																 array("valor"=>"<br><b>Tipo Doc. : </b>"),
																 array("valor"=>3, "tipo"=>"INDEX"),
																 array("valor"=>"<br><b>Documento : </b>"),
																 array("valor"=>4, "tipo"=>"INDEX")
												   				),
												 "click"=>array("funcion"=>"fn_dirigir_registro",
																"param"=>array(array("valor"=>"VIEW", "tipo"=>"TEXTO"),
																			   array("valor"=>0, "tipo"=>"INDEX"),
																			   array("valor"=>$Link, "tipo"=>"TEXTO")
																			   )
																)
												 )
										)
							);
			echo $obj->SetGridTabla($varTabla);
			}
		}
elseif($Opcion=="VIEW") {
	$sql = "CALL spQuery_Registro_Compras_Cabecera($Valor)";
	echo $sql;
	$obj->AbrirConexion();
	$rs = $obj->Query($sql);
	$obj->CerrarConexion();
	$Fila = $obj->FetchArray($rs);
	$varFlagIgv = array("S" => "PRECIOS SI INCLUYEN IGV", "N" => "PRECIOS NO INCLUYEN IGV");
	
	echo "<form id=\"form\" name=\"form\" method=\"POST\"  onSubmit=\"return validaRegistroCompra(this)\">";
	
	$varTabla=array("id"=>"tabla", "name"=>"table", "tamano"=>"400", "clase"=>"Formtitulo", "titulo"=>$Titulo." - DETALLE",						
						"ocult"=>array(array("tipo"=>"oculto", "id"=>"titu", "name"=>"titu", "valor"=>$Titulo),
									   array("tipo"=>"oculto", "id"=>"opt",  "name"=>"opt",  "valor"=>$Opcion),
									   array("tipo"=>"oculto", "id"=>"ide",  "name"=>"ide",  "valor"=>$Valor)
									  ),
						"conte"=>array(array("titulo"=>"Fecha Emision :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
											 "texto"=>$Fila["FEMI"], "tamano"=>"120"),
									   array("titulo"=>"Fecha Movimiento :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
											 "texto"=>$Fila["FMOV"]),
									   array("titulo"=>"Documento :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
									   		 "texto"=>$Fila["CTIP"]." &nbsp; ".$Fila["NDOC"]),
									   array("titulo"=>"Proveedor :", "clase1"=>"FormCampo1", "clase2"=>"interior",
										     "texto"=>$Fila["CPRO"].' - '.$Fila["PROVEEDOR"]),
									   array("titulo"=>"Sub Total :", "clase1"=>"FormCampo1", "clase2"=>"interior",
										     "texto"=>number_format($Fila["SUBTOTAL"], 2,'.',',')),
									   array("titulo"=>"IGV :", "clase1"=>"FormCampo1", "clase2"=>"interior",
										     "texto"=>number_format($Fila["IGV"], 2,'.',',')),
									   array("titulo"=>"Total :", "clase1"=>"FormCampo1", "clase2"=>"interior",
										     "texto"=>number_format($Fila["TOTAL"], 2,'.',',')),
									   array("titulo"=>"Estado :", "clase1"=>"FormCampo1", "clase2"=>"interior",
										     "texto"=>$Fila["ESTADO"]),
									   array("titulo"=>"F/U Creado :", "clase1"=>"FormCampo1", "clase2"=>"interior",
										     "texto"=>$Fila["USER_CREATE"]." &nbsp; - &nbsp; ".$Fila["DATE_CREATE"]),
									   array("titulo"=>"F/U Modificado :", "clase1"=>"FormCampo1", "clase2"=>"interior",
										     "texto"=>$Fila["USER_UPDATE"]." &nbsp; - &nbsp; ".$Fila["DATE_UPDATE"]),
									   array("titulo"=>"Tipo Datos :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
										     "campo"=>array("tipo"=>"select_simple", "id"=>"flag_igv", "name"=>"flag_igv", "valor"=>$_POST["flag_igv"], 
											 				"ancho"=>"100", "combo"=>array("sql"=>$varFlagIgv, "sincod"=>"SI", "ancho"=>"200",
															"reload"=>"javascript:CalculaRTotal()")))
									   ),
						"boton"=>array(array("tipo"=>"button", "id"=>"breg", "name"=>"breg", "ancho"=>"100", "alto"=>"22", 
											 "texto"=>"Regresar", "click"=>"location='$Link'")
									   )
						);
		echo $obj->setTablaForm($varTabla);		
		
		$sql = "select D.id_producto AS CPRO, A.descripcion AS PRODUCTO, D.id_um as UM, 
				D.PRECIO_CON_IGV as PRECIO, D.CANTIDAD, IFNUlL(D.PORC_DESC1,0) AS DESC1, IFNULL(D.PORC_DESC2,0) AS DESC2, D.SUBTOTAL, D.IGV, D.TOTAL
				from _sv_compra_detalle D
				inner join _sv_producto A ON D.id_producto = A.id_producto
				where D.id_compra=$Valor";
		$obj->AbrirConexion();
		$rs = $obj->Query($sql);
		$obj->CerrarConexion();
		
		$NumReg = $obj->NumFilas($rs);
		echo "<table id=\"tblSample\" style=\"padding:0;margin-top:0px;border-collapse:collapse;\" ";
		echo "width=770 align=center cellpadding=0 cellspacing=0>";
		echo "<tr>";
		echo "<td class=\"FormCampo2\" width=\"90\">Codigo";
		echo "<input name=\"num\" type=\"hidden\" class=\"input\" id=\"num\" value=\"".$NumReg."\"/>";
		echo "</td>";	
		echo "<td class=\"FormCampo2\" width=\"360\">Descripcion</td>";
		echo "<td class=\"FormCampo2\" width=\"50\">UM Compra</td>";
		echo "<td class=\"FormCampo2\" width=\"50\">Precio</td>";
		echo "<td class=\"FormCampo2\" width=\"50\">Cantidad</td>";
		echo "<td class=\"FormCampo2\" width=\"50\">Desc.1</td>";
		echo "<td class=\"FormCampo2\" width=\"50\">Desc.2</td>";
		echo "<td class=\"FormCampo2\" width=\"50\">Total</td>";
		echo "<td class=\"FormCampo2\" width=\"10\"></td>";
		echo "</tr>";
		echo "<tbody id=cuerpoTabla>";
		
		$i = 0;
		$varSubTotal = 0;
		$varIgv = 0;
		$varTotal = 0;
		while ($fila = $obj->FetchArray($rs)) {	
			$i++;
			$varSubTotal = $varSubTotal + $fila[SUBTOTAL];
			$varIgv = $varIgv + $fila[IGV];
			$varTotal = $varTotal + $fila[TOTAL];
			echo "<tr bgcolor=\"#F5FAFA\" onmouseover=\"uno(this,'#FFFF33')\" onmouseout=\"dos(this,'#F5FAFA')\" style=\"cursor: default;\">";
			echo "<td align=\"center\" class=\"interior\">";
			echo "<input name=\"icod[".$i."]\" id=\"icod[".$i."]\" type=\"text\" readonly  class=\"inputDisable\" onkeypress=\"return SoloEnteros(event)\" ";
			echo "style=\"text-align:center; width:80px\" value=\"".$fila[CPRO]."\" >";
			echo "</td>";
			echo "<td class=\"interior\">";
			echo "<input name=\"inom[".$i."]\" id=\"inom[".$i."]\" type=\"text\" style=\"width:350px\" readonly class=\"inputDisable\" ";
			echo "value=\"".$fila[PRODUCTO]."\" >";
			echo "</td>";
			echo "<td class=\"interior\">";
			echo "<input name=\"iuni[".$i."]\" id=\"iuni[".$i."]\" type=\"text\" style=\"text-align:center; width:50px\" readonly class=\"inputDisable\" ";
			echo "value=\"".$fila[UM]."\" >";
			echo "</td>";
			echo "<td align=\"center\" class=\"interior\">";
			echo "<input name=\"ipre[".$i."]\" id=\"ipre[".$i."]\" type=\"text\" style=\"text-align:right;width:60px\" autocomplete=\"off\" ";
			echo "onkeyup=\"CalcularItem('".$i."')\" onkeypress=\"return SoloNumeros(event)\" value=\"".$fila[PRECIO]."\" >";
			echo "</td>";
			echo "<td align=\"center\" class=\"interior\">";
			echo "<input name=\"ican[".$i."]\" id=\"ican[".$i."]\" type=\"text\" style=\"text-align:right;width:50px\" autocomplete=\"off\" ";
			echo "onkeyup=\"CalcularItem('".$i."')\"  value=\"".$fila[CANTIDAD]."\" >";
			echo "</td>";
			echo "<td align=\"center\" class=\"interior\">";
			echo "<input name=\"ides1[".$i."]\" id=\"ides1[".$i."]\" type=\"text\" style=\"text-align:right;width:40px\" autocomplete=\"off\" ";
			echo "onkeyup=\"CalcularItem('".$i."')\" onkeypress=\"return SoloNumeros(event)\" value=\"".$fila[DESC1]."\"  >";
			echo "</td>";
			echo "<td align=\"center\" class=\"interior\">";
			echo "<input name=\"ides2[".$i."]\" id=\"ides2[".$i."]\" type=\"text\" style=\"text-align:right;width:40px\" autocomplete=\"off\" ";
			echo "onkeyup=\"CalcularItem('".$i."')\" onkeypress=\"return SoloNumeros(event)\" value=\"".$fila[DESC2]."\" >";
			echo "</td>";
			echo "<td align=\"center\" class=\"interior\">";
			echo "<input name=\"itot[".$i."]\" id=\"itot[".$i."]\" type=\"text\" style=\"text-align:right;width:60px\"  autocomplete=\"off\" ";
			echo "onkeyup=\"CalcularItemSubTotal('".$i."')\" onkeypress=\"return SoloNumeros(event)\" value=\"".$fila[TOTAL]."\" >";
			echo "</td>";
			echo "<td align=\"center\" class=\"interior\"></td>";
			echo "</tr>";
			}
		echo "</tbody>";
		echo "<tr>";
		echo "<td height=19 class=\"interior\" colspan=7 align=\"right\"><b>Sub Total :</b></td>";	
		echo "<td align=\"center\" class=\"interior\">";
		echo "<input name='stot' id='stot' type='text' class='inputDisable' readonly style='text-align:right;width:60px' ";
		echo "value=\"".round($varSubTotal,2)."\" />";
		echo "</td>";
		echo "<td class=\"interior\"></td>";
		echo "</tr>";
		echo "<tr>";
		echo "<td height=19 class=\"interior\" colspan=7 align=\"right\"><b>Igv :</b></td>";	
		echo "<td align=\"center\" class=\"interior\">";
		echo "<input name='igv' id='igv' type='text' class='inputDisable' readonly style='text-align:right;width:60px' value=\"".round($varIgv,2)."\" />";
		echo "</td>";
		echo "<td class=\"interior\"></td>";
		echo "</tr>";
		echo "<tr>";
		echo "<td height=19 class=\"interior\" colspan=7 align=\"right\"><b>Total :</b></td>";	
		echo "<td align=\"center\" class=\"interior\">";
		echo "<input name='tot' id='tot' type='text' class='inputDisable' readonly style='text-align:right;width:60px' value=\"".round($varTotal,2)."\" />";
		echo "</td>";
		echo "<td class=\"interior\"></td>";
		echo "</tr>";
		echo "<tr>";
		echo "<td height=25 colspan=10 valign=top aling=\"center\" class=\"FormTitulo\">";	
		echo "<input id=\"save\" name=\"save\" type=\"submit\" style=\"width:150px; ";
		echo "height:22px; font-size:10px; \" value=\"Registrar Documento\" onClick=\"return confirm('¿DESEA GUARDAR EL MOVIMIENTO?')\" >";
		echo "</td>";
		echo "</tr>";
		echo "</table>";
		echo "</form>";
		}
	
if(isset($_POST["save"])) {
	$Usr = (isset($_SESSION["_CUSE"]))  ? $_SESSION["_CUSE"] : "1";
	$vnum = $_POST["num"];
	$femi = FechaMySql($_POST["femi"]);
	$fmov = FechaMySql($_POST["fmov"]);	
	
	$varTotal = $_POST["tot"];
	$varLoc = 1;
	$varPro = (isset($_POST["pcod"]) && $_POST["pcod"]<>"")?$_POST[pcod] : "NULL";
	$varPrN = (isset($_POST["pnom"]) && $_POST["pnom"]<>"")?"'".$_POST[pnom]."'": "NULL";	
	$varCon = (isset($_POST["con"]) && $_POST["con"]<>"")?$_POST[con]:"NULL";
	$varGlo = (isset($_POST["glos"]) && $_POST["glos"]<>"")?"'".$_POST[glos]."'":"NULL";
	$varFlagIgv = (isset($_POST["flag_igv"]) && $_POST["flag_igv"]<>"")?$_POST[flag_igv]:"N";
	
	$NumCompra = $_POST[ide];
	
	$sql = "call spMante_Compra_Cab_Update($NumCompra, $_POST[tot], $Usr);";
	//echo $sql."<br>";
	$obj->AbrirConexion();
	$obj->Query($sql);
	$obj->CerrarConexion();
	$Fila = $obj->FetchArray($rs);
	
	for($i=1; $i<=$vnum; $i++) {		
		$vcod = $_POST["icod"][$i];
		$varPre = (isset($_POST["ipre"][$i])  && $_POST["ipre"][$i] <> "")?$_POST["ipre"][$i]:0;
		$varCan = (isset($_POST["ican"][$i])  && $_POST["ican"][$i] <> "")?$_POST["ican"][$i]:0;
		$varDes1= (isset($_POST["ides1"][$i]) && $_POST["ides1"][$i]<> "")?$_POST["ides1"][$i]:0;
		$varDes2= (isset($_POST["ides2"][$i]) && $_POST["ides2"][$i]<> "")?$_POST["ides2"][$i]:0;
		$varUme = (isset($_POST["iuni"][$i])  && $_POST["iuni"][$i] <> "")?$_POST["iuni"][$i]:"";
		$varTot = $varPre*$varCan;
	
		$sql = "call spMante_Compra_Det_Update($NumCompra, '$varFlagIgv',  '$vcod',  $varCan, $varPre, $varDes1, $varDes2, $Usr)";		
		//echo $sql."<br>";
		$obj->AbrirConexion();
		$obj->Query($sql);
		$obj->CerrarConexion();
		}
	echo "<script language='Javascript'>";
	echo "window.location='$Link'";
	echo "</script>\n";
	}
} 
?>