
function cadenaPost(divID){
	/*
		Funcion que prepara cadenas de post para mandar mandar elementos HTML por post como si fueran formularios.
		Aplica para:
			input
				+ text
				+ checkbox
				+ radio
				+ hidden
			textarea
			select
		
		Modo de uso:
			llamar a la funcion pasandole el ID del elemento que contiene los campos a mandar.
			EJ: cadena = cadenaPost("divformulario");
			
			Devolvera en la variable cad la cadena para enviar por post.
				ej: nombre=Juan&apellido=Caseres&telefono=22222
	*/
	

	E = document.getElementById(divID);
	inputs = E.getElementsByTagName('input');
	textareas =	E.getElementsByTagName('textarea');
	selects = E.getElementsByTagName('select');

	str = "";
	
	for (i=0; i< inputs.length; i++){
		if(inputs[i].type == "radio"){
			if(inputs[i].checked){
				if(str != ""){
					str += "&";
				}
				str += inputs[i].name + "=" + inputs[i].value;
			}
		}else if (inputs[i].type == "checkbox"){
			if(inputs[i].checked){
				if(str != ""){
					str += "&";
				}
				str += inputs[i].name + "=" + inputs[i].value;
			}
		} else {
			if(str != ""){
				str += "&";
			}
			str += inputs[i].name + "=" + inputs[i].value;
		}
	}
	
	for (i=0; i< textareas.length; i++){
		if(str != ""){
			str += "&";
		}
		str += textareas[i].name + "=" + textareas[i].value;
	}
	
	for (i=0; i< selects.length; i++){
		if(str != ""){
			str += "&";
		}
		str += selects[i].name + "=" + selects[i].value;
	}
	
	return(str);
}

function guardar_seccion_directo(seccion, id){
	/*
		Funcion no probada en su totalidad, Volar este renglon cuando se termine. Secciones probadas con //# al final
	
		Secciones son las del switch de abajo.
		ID corresponde al id de lote directo.
		P corresponde a permisos R = lectura. W = escritura.
	*/

	// CAPA A REEMPLAZAR;
      
	capa = document.getElementById(seccion);
	
	cad = cadenaPost(seccion);
	document.getElementById("loader2_" + seccion).innerHTML = '<div class="loadx"></div>';
	if(isNaN(id)){
		alert ("Hay un error de parametros, no puede continuar.");
		return false;
	}
	
	switch (seccion){
		case "ofrecimiento_directo":
			archivo = "ofr dire";
		case "condiciones_negocio":
			archivo = "n_directo/form_ajax/form_negocio.php";
			break;
		case "resumen":
			archivo = "n_directo/form_ajax/form_resumen.php";
			break;	
		case "archivos_multimedia":
			archivo = "n_directo/form_ajax/form_multimedia.php";
			break;
		case "comentarios_publicacion":
			archivo = "n_directo/form_ajax/form_comentario.php";
			break;
		case "informacion_comprador":
			archivo = "n_directo/form_ajax/form_comprador.php"; //#
			break;
		case "informacion_frigorifico":
			archivo = "n_directo/form_ajax/form_frigorifico.php"; 
			break;
		case "condiciones_operativas":
			archivo = "n_directo/form_ajax/form_operativa.php";
			break;
		case "informacion_origen":
			archivo = "n_directo/form_ajax/form_origen.php";
			break;
		
		case "informacion_origen_cliente":
			archivo = "n_usuarios/form_ajax/form_origen.php";
			break;
		
		case "informacion_planta":
			archivo = "n_directo/form_ajax/form_planta.php";
			break; 
		case "informacion_cierre":
			archivo = "n_directo/form_ajax/form_cierre.php";
			break;
		case "archivos_romaneo":
			archivo = "n_directo/form_ajax/form_romaneos.php";
			break;
		case "archivos_liquidaciones":
			archivo = "n_directo/form_ajax/form_liquidaciones.php";
			break;
	}
	
	ajax=objetoAjax();

	ajax.open("POST", archivo + "?perm=R" ,true);
	
	ajax.onreadystatechange=function() {
	
		if (ajax.readyState!=4){
			
			document.getElementById("loader2_" + seccion).innerHTML = '<div class="loadx"></div>';
		
		}
		if (ajax.readyState==4){
			capa.innerHTML = ajax.responseText;
			if(seccion == "informacion_comprador" || seccion == "informacion_frigorifico"){
				refresh_envio_destinos(id);
			}
		}			
	}	
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	
	if(cad){
		
		ajax.send(cad + "&directo="+ id + "&guardar=true");
	}else{
		alert("Algo fallo");
		ajax.send("directo="+ id);
	}
	return true;
}


function refresh_envio_destinos(id){
	ajax=objetoAjax();
	archivo = "n_directo/form_ajax/form_destinos.php";
	
	ajax.open("POST", archivo,true);
	
	capa = document.getElementById("enviar_destinos");
	
	ajax.onreadystatechange=function() {
	
		if (ajax.readyState!=4){
			document.getElementById("loader_" + seccion).innerHTML = '<div class="loadx"></div>';
			
			//if(!(navigator.appName == "Microsoft Internet Explorer") && !(navigator.appVersion > 5)){
			//	new Effect.Opacity(Resultado, { from: 1, to: 0, duration: 0 });
			//}
		}
		if (ajax.readyState==4){
			capa.innerHTML = ajax.responseText;
			//createPickers_hora();
			//createPickers();
			//if(!(navigator.appName == "Microsoft Internet Explorer") && !(navigator.appVersion > 5)){
			//	new Effect.Opacity(Resultado, { from: 0, to: 1, duration: 1 });
			//}
		}
	}	
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("directo="+ id);
    
}

function editar_seccion_directo(seccion, id, P){
	/*
		Funcion no probada en su totalidad, Volar este renglon cuando se termine. Secciones probadas con //# al final
	
		Secciones son las del switch de abajo.
		ID corresponde al id de lote directo.
		P corresponde a permisos R = lectura. W = escritura.
	*/
	
	// CAPA A REEMPLAZAR;
        
	capa = document.getElementById(seccion);
	
	 document.getElementById("loader_" + seccion).innerHTML = '<div class="loadx"></div>';
	if(isNaN(id)){
		alert ("Hay un error de parametros, no puede continuar.");
		return false;
	}
	else{
	//	alert("seccion: " + seccion + "\n id: " + id);
	}
	
	switch (seccion){
		case "ofrecimiento_directo":
			archivo = "ofr dire";
		case "condiciones_negocio":
			archivo = "n_directo/form_ajax/form_negocio.php";
			break;
		case "resumen":
			archivo = "n_directo/form_ajax/form_resumen.php";
			break;	
		case "archivos_multimedia":
			archivo = "n_directo/form_ajax/form_multimedia.php";
			break;
		case "comentarios_publicacion":
			archivo = "n_directo/form_ajax/form_comentario.php";
			break;
			
		case "informacion_comprador":
			archivo = "n_directo/form_ajax/form_comprador.php"; //#
			break;
		case "informacion_frigorifico":
			archivo = "n_directo/form_ajax/form_frigorifico.php"; 
			break;
		case "condiciones_operativas":
			archivo = "n_directo/form_ajax/form_operativa.php";
			break;
		case "informacion_origen":
			archivo = "n_directo/form_ajax/form_origen.php";
			break;
		case "informacion_origen_cliente":
			archivo = "n_usuarios/form_ajax/form_origen.php";
			break;			
		case "informacion_planta":
			archivo = "n_directo/form_ajax/form_planta.php";
			break; 
		case "informacion_cierre":
			archivo = "n_directo/form_ajax/form_cierre.php";
			break;
		case "archivos_romaneo":
			archivo = "n_directo/form_ajax/form_romaneos.php";
			break;
		case "archivos_liquidaciones":
			archivo = "n_directo/form_ajax/form_liquidaciones.php";
			break;
	}
	
	ajax=objetoAjax();
	
	ajax.open("POST", archivo + "?perm=" + P ,true);
	
	ajax.onreadystatechange=function() {
	
		if (ajax.readyState!=4){
			document.getElementById("loader_" + seccion).innerHTML = '<div class="loadx"></div>';
			
			//if(!(navigator.appName == "Microsoft Internet Explorer") && !(navigator.appVersion > 5)){
			//	new Effect.Opacity(Resultado, { from: 1, to: 0, duration: 0 });
			//}
		}
		if (ajax.readyState==4){
			
			capa.innerHTML = ajax.responseText;
			createPickers_hora();
			createPickers();
			//if(!(navigator.appName == "Microsoft Internet Explorer") && !(navigator.appVersion > 5)){
			//	new Effect.Opacity(Resultado, { from: 0, to: 1, duration: 1 });
			//}
		}			
	}	
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("directo="+ id);
	
}

function cb(t)
{
	if(t.title=="Si")
	{
		t.src="imagenes/cross.png";
		t.title="No";
	}
	else
	{
		t.src="imagenes/tick.png";
		t.title="Si";
	}
}

function cbs(t)
{
	if(t.title=="Si")
	{
		t.src="imagenes/cross.png";
		t.title="Si";
	        inp = document.getElementById("inp");
		inp.value=0;
		
		
		
	}
	else if(t.title=="No")
	{
		t.src="imagenes/tick.png";
		t.title="No";
		inp = document.getElementById("inp");
		inp.value=1;
		
		
		
	}
}

function resp_oferta(v)
{
	switch(v)
	{
		case 1:
			$('titulo_resp').innerHTML = 'Oferta Baja - Con Referencias';
			$('mensaje').value = 'Hemos recibido su oferta por el lote #'+$("revisacion").value+' \n\nya se ha pasado una oferta superior, en todo caso lo consultamos si la misma no prospera.';
			break
		case 2:
			$('titulo_resp').innerHTML = 'Oferta Baja - Sin Referencias';
			$('mensaje').value = 'Hemos recibido su oferta por el lote #'+$("revisacion").value+' \n\nya se ha pasado una oferta superior, en todo caso lo consultamos si la misma no prospera.\n\nNecesitamos que complete en su <b>perfil</b> en deCampoaCampo los datos de la sociedad y \nsus referencias comerciales correspondientes para que el sector de creditos pueda asignarle una linea crediticia.\n_LINK_';
			break
		case 3:
			$('titulo_resp').innerHTML = 'Oferta Ok - Con Referencias';
			$('mensaje').value = 'Hemos recibido su oferta por el lote #'+$('revisacion').value+' \n\nLa misma ya fue enviada al vendedor, \nni bien tengamos una respuesta nos comunicaremos con usted.';
			break
		case 4:
			$('titulo_resp').innerHTML = 'Oferta Ok - Sin Referencias';
			$('mensaje').value = 'Hemos recibido su oferta por el lote #'+$('revisacion').value+' \n\nNecesitamos que complete en su <b>perfil</b> en deCampoaCampo los datos de la sociedad y sus referencias comerciales correspondientes para que el sector de creditos pueda asignarle una linea crediticia.\n_LINK_';
			break
		case 5:
			$('titulo_resp').innerHTML = 'Oferta Ok - Malas Referencias';
			$('mensaje').value = 'Hemos recibido su oferta por el lote #'+$('revisacion').value+' \n\nEl sector de creditos nos aprueba la misma unicamente con pago contado.';
			break
	}
	Effect.toggle('resp', 'blind',{duration: 0.2});
	Effect.toggle('posteo', 'blind',{duration: 0.2});
	$('respuesta').value = v;

	if(v!=0)
	{
		$('mensaje').value += '\n\nSaludos Cordiales\n\nEl equipo de deCampoaCampo.com\n\nTel: 0810-222-0900'; 
	}
	
}
 
 
 
 
function ordenar_lote()
{
	if($('guardar_orden').style.display=='none')
	{
		$$('.ocultar').each(Element.hide);
		$$('.mostrar').each(Element.show);
		$('guardar_orden').style.display = '';
		$('boton_ordenar').innerHTML = 'Cancelar';

		Sortable.create(
				'movete',
				{
					elements: $$('#movete .ordenar'),
					scrollSensitivity: 40,
					scrollSpeed: 20,
					handles: $$('.mover'),
					scroll: window
				}
		);
	}
	else
	{
		$$('.ocultar').each(Element.show);
		$$('.mostrar').each(Element.hide);
		$('guardar_orden').style.display = 'none';
		$('boton_ordenar').innerHTML = 'Ordenar Lotes';
	}
}

function asignar_adm(t)
{
	var sel = $(t).up().down('select').value;
	var rev = $(t).up().down('input:first').value;

	var data = 'revisacion='+rev+'&select_admin='+sel+'&guardar_adm_solicitud=1';

	new posteoAjax('lotes_publicados.php',data,'contenedor_main','1','1');
}

function cambiar_estado()
{
	var inputs = document.getElementsByTagName('input');
	var estado = document.getElementById('estado_cambiar').value;
	var data = 'estado='+estado;
	var seleccionados = 0;

	for(i=0; i<inputs.length; i++)
	{
		if(inputs[i].type == "checkbox")
		{
			if(inputs[i].checked == true)
			{
				data += '&lotes[]=' + inputs[i].value;
				seleccionados++; 
			}
		}
	}

	if(seleccionados==0) {alert("No se seleccion� ning�n lote");return false;}

	new posteoAjax('lotes_publicados.php',data,'contenedor_main','1','1'); 
}
function buscar(f)
{
	if(f.busca.value.length > 2)
	{
		if(IsNumeric(f.busca.value)) {loteA(f.busca.value);return false;}

		posteoAjax('buscador.php',f,'busca','1','2');

		document.getElementById('ver_busc').style.display = '';
		document.getElementById('ver_busc').className = 'ba ico_disa';
		document.getElementById('busca_i').style.width = '72px';
	}
}
function busqueda(t)
{
	if(!t) {
		document.getElementById('ver_busc').style.display = '';
		document.getElementById('busca_i').style.width = '75px !important';
	}

	var div = document.getElementById('busca');
	Effect.toggle(div, 'Appear', {duration: 0.25} );
	if(t.className=='ba ico_able') {t.className='ba ico_disa';} else {t.className='ba ico_able';}
}

function cerrar_negocio(x)
{
	if(document.getElementById('boton1')) document.getElementById('boton1').style.display="none";
	if(document.getElementById('boton2')) document.getElementById('boton2').style.display="none";
	doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'dd/MM/yyyy' });";

	new posteoAjax('agregar_negocio_tropa.php','cerrar='+x,'cerrar','1','1',doit);
}

function liquidar_negocio(x)
{
	if(document.getElementById('boton1')) document.getElementById('boton1').style.display="none";
	if(document.getElementById('boton2')) document.getElementById('boton2').style.display="none";
	new posteoAjax('liquidar_negocio.php','liquidar='+x,'liquidar','1','1');
}

function liquidar_negocio_directo(x)
{
	if(document.getElementById('boton1')) document.getElementById('boton1').style.display="none";
	if(document.getElementById('boton2')) document.getElementById('boton2').style.display="none";
	new posteoAjax('liquidar_negocio_directo.php','liquidar='+x,'liquidar','1','1');
}

function nuevo_frigorifico()
{
	var f = document.getElementById('form_tropa');
	document.getElementById('frig_colgado').innerHTML = '<div class="fake" style="width:auto">Ingrese uno nuevo o bien intente otra busqueda</div>';

	f.nombre_frigorifico.value = '';
	f.direccion.value = '';
	f.oncca.value = '';
	f.cuit.value = '';
	f.nombre_frigorifico.focus();
}

function calculo_org(f)
{        
    
	kg_entrada = f.kg_entrada.value;
	kg_carne = f.kg_carne.value;
         
	kg_salida_neto = f.kg_salida_neto.value;
      

	if(kg_carne>0)
	{
		if(kg_entrada>0)
		{
			
                        var rplanta = ((kg_carne/kg_entrada)*100).toFixed(2);
			document.getElementById('rendimiento_planta').innerHTML = rplanta+' ';
			document.getElementById('rendimiento_planta_i').value = rplanta;
		}
		if(kg_salida_neto>0)
		{ 
                   // alert(kg_salida_neto);
			var rcampo = ((kg_carne/kg_salida_neto)*100).toFixed(2);
			document.getElementById('rendimiento_campo').innerHTML = rcampo+' ';
			document.getElementById('rendimiento_campo_i').value = rcampo;
		}
	}
}
var autocal = 1;
function autocalc(t)
{
	if(autocal==0)
	{
		autocal = 1;
		t.className = 'verdee';
	}
	else
	{
		autocal = 0;
		t.className = 'rojoo';
	}
}

function neto_bruto(t)
{
	if(autocal==0) return;

	if(t.name=="kg_salida_bruto")
	{
		var neto = document.getElementById("neto_I");
		var desb = document.getElementById("desb_I").value;
		neto.value = parseInt(t.value * (100 - desb) / 100);
               
	}
	else
	{
		var bruto = document.getElementById("bruto_I");
		var desb = document.getElementById("desb_I").value;
		bruto.value = parseInt(t.value / (100 - desb) * 100);
               
	}
}


function notif_neg(x,e)
{
	var agr = document.getElementById('agregar');

	new posteoAjax('notificar_negocio.php','negocio='+x,'agregar',1,1);
	agr.setAttribute("name",x);
}

function agr_negocio(x,e)
{
	var agr = document.getElementById('agregar');
	
	if(agr.style.display=="" && agr.getAttribute("name")==x && !e)
	{
		new Effect.Fade(agr,{duration: 0.03});
	}
	else if(x=='x')
	{
		new Effect.Fade(agr, {duration: 0.03});
		if($$('.neg_flot')[0]) {
			$$('.neg_flot')[0].hide();
		}
	}
	else if(x=='a')
	{
		new posteoAjax('agregar_negocio.php','agregar=1','agregar','1','1');
		agr.setAttribute("name","0");
	}
	else
	{
		add = '';

		if(e=='e') {add += 'editar=e&'}

		if(e=='n') {add += 'noguardar=3&'}

		if(e=='f') {
			doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'dd/MM/yyyy' });";
		}
		else
		{
			doit = "";
		}

		if(e=='n') {
			$$('.neg_flot')[0].show();
			new posteoAjax('agregar_negocio_flotante.php',add+'negocio='+x,'agregar','1','1',doit);
			
			$$('.neg_flot')[0].observe('onclick',function(){
				$$('.neg_flot')[0].hide();
			});
			
		}
		else {
		 	if(e == 'ofrecimientos_e') 
			{
				add += 'editar=e&';
				new posteoAjax('agregar_negocio.php?desde=1',add+'negocio='+x,'agregar','1','1',doit);
			}
		 	else if(e == 'ofrecimientos_e_noed') {new posteoAjax('agregar_negocio.php?desde=1&noeditar=1',add+'negocio='+x,'agregar','1','1',doit);}

			else if(e == 'publicados_e') 
			{
				add += 'editar=e&';
				new posteoAjax('agregar_negocio.php?desde=2',add+'negocio='+x,'agregar','1','1',doit);
			}
			else if(e == 'publicados_e_noed') {new posteoAjax('agregar_negocio.php?desde=2&noeditar=1',add+'negocio='+x,'agregar','1','1',doit);}
			
			else if(e == 'vendidas_e') 
			{
			//	add += 'editar=e&';
				doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'dd/MM/yyyy' });";
				new posteoAjax('agregar_negocio.php?desde=3',add+'negocio='+x,'agregar','1','1',doit);
			}
			else if(e == 'liquidaciones_e') 
			{
				add += 'editar=e&';
				new posteoAjax('agregar_negocio.php?desde=4',add+'negocio='+x,'agregar','1','1',doit);
			}
			else if(e == 'liquidaciones_e_noed') {new posteoAjax('agregar_negocio.php?desde=4',add+'negocio='+x,'agregar','1','1',doit);}
	
			else
			{
				new posteoAjax('agregar_negocio.php',add+'negocio='+x,'agregar','1','1',doit);
			}
		}

		agr.setAttribute("name",x);
//		setTimeout("document.forms[0].aclaracion.focus()",500);
	}
}

function agr_negocio_directo(x,e)
{
	var agr = document.getElementById('agregardirecto');
	
	if(agr.style.display=="" && agr.getAttribute("name")==x && !e)
	{
		new Effect.Fade(agr,{duration: 0.03});
	}
	else if(x=='x')
	{
		new Effect.Fade(agr, {duration: 0.03});
		if($$('.neg_flot')[0]) {
			$$('.neg_flot')[0].hide();
                        
                      
                     
                       
                        
		}
	}
	else if(x=='a')
	{
		new posteoAjax('n_directo/indice_directo.php','agregar=1','agregardirecto','1','1');
		agr.setAttribute("name","0");
	}
	else
	{
		add = '';

		if(e=='e') {add += 'editar=e&'}

		if(e=='n') {add += 'noguardar=3&'}

		if(e=='f') {
			doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'dd/MM/yyyy' });";
		}
		else
		{
			doit = "";
		}

		if(e=='n' || e=='n_esp') {
			$$('.neg_flot')[0].show();
	
			if(e=='n') {
				new posteoAjax('agregar_negocio_flotante_directo.php',add+'negocio='+x,'agregar','1','1',doit);
			}
			else {
				new posteoAjax('agregar_negocio_flotante_directo.php?nomasinfo=1',add+'negocio='+x,'agregar','1','1',doit);
			}
			
			$$('.neg_flot')[0].observe('onclick',function(){
				$$('.neg_flot')[0].hide();
			});
			
		}
		else {
			doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'dd/MM/yyyy' });";
			
		 	if(e == 'ofrecimientos_e') 
			{
				doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' }); new Control.DatePicker(document.getElementById('fin_subasta_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' });";
				add += 'editar=e&';
				new posteoAjax('n_directo/indice_directo.php?desde=1',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
		 	else if(e == 'ofrecimientos_e_noed') { 
				doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' }); new Control.DatePicker(document.getElementById('fin_subasta_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' });";
				new posteoAjax('n_directo/indice_directo.php?desde=1&noeditar=1',add+'negocio='+x,'agregardirecto','1','1',doit);
			}

			else if(e == 'publicados_e') 
			{
				doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' }); new Control.DatePicker(document.getElementById('fin_subasta_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' });";
				add += 'editar=e&';
				new posteoAjax('n_directo/indice_directo.php?desde=2',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
			else if(e == 'publicados_e_noed') { 
				doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' }); new Control.DatePicker(document.getElementById('fin_subasta_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' });";
				new posteoAjax('n_directo/indice_directo.php?desde=2&noeditar=1',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
			
			else if(e == 'vendidas_e') 
			{
				add += 'editar=e&';
				//doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' });";
				new posteoAjax('n_directo/indice_directo.php?desde=3',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
			else if(e == 'liquidaciones_e') 
			{
				add += 'editar=e&';
				new posteoAjax('n_directo/indice_directo.php?desde=4',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
			else if(e == 'liquidaciones_e_noed') {new posteoAjax('n_directo/indice_directo.php?desde=4',add+'negocio='+x,'agregardirecto','1','1',doit);}
			else if(e == 'vendidas_e_noed') 
			{
			//	add += 'editar=e&';
			//	doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' });";
				new posteoAjax('n_directo/indice_directo.php?desde=3',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
			else if(e == 'vendidas_especial_cliente') 
			{
				doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' });";
				new posteoAjax('n_usuarios/indice_usuarios.php',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
                        else if(e == 'compras_especial_cliente') 
			{
				doit = "new Control.DatePicker(document.getElementById('fecha_I'), { icon: '/cal/calendar.png', dateFormat: 'yyyy-MM-dd 00:00:00' });";
				new posteoAjax('n_usuarios/indice_usuarios.php',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
			else if(e == 'cerrados_final_e') 
			{
				add += 'editar=e&';
				new posteoAjax('n_directo/indice_directo.php?desde=5',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
			else if(e == 'cerrados_final_e_noed') {new posteoAjax('n_directo/indice_directo.php?desde=5',add+'negocio='+x,'agregardirecto','1','1',doit);}
			
			else
			{
				new posteoAjax('n_directo/indice_directo.php',add+'negocio='+x,'agregardirecto','1','1',doit);
			}
		}

		agr.setAttribute("name",x);
//		setTimeout("document.forms[0].aclaracion.focus()",500);
	}
}

var ccc = 1;

function editarTropa() //Enablea la informacion del comprador, frigorifico, y precios/plazos/etc.
{
	document.getElementById("bmc").disabled = false;
	document.getElementById("bm").disabled = false;
	document.getElementById("bf").disabled = false;
	document.getElementById("precio1_I").disabled = false;
	document.getElementById("plazo1_I").disabled = false;
	document.getElementById("precio2_I").disabled = false;
	document.getElementById("plazo2_I").disabled = false;
	document.getElementById("iva1_I").disabled = false;
	document.getElementById("final1_I").disabled = false;
	document.getElementById("iva2_I").disabled = false;
	document.getElementById("final2_I").disabled = false;
	document.getElementById("kiloVivo_I").disabled = false;
	document.getElementById("kiloCarne_I").disabled = false;
	document.getElementById("kiloVivo2_I").disabled = false;
	document.getElementById("kiloCarne2_I").disabled = false;
	document.getElementById("puesto_I").disabled = false;
	document.getElementById("comision_I").disabled = false;
	document.getElementById("fecha_I").disabled = false;
	
	document.getElementById("bmc").style.backgroundColor = "#ffffff";
	document.getElementById("bm").style.backgroundColor = "#ffffff";
	document.getElementById("bf").style.backgroundColor = "#ffffff";
	document.getElementById("precio1_I").style.backgroundColor = "#ffffff";
	document.getElementById("plazo1_I").style.backgroundColor = "#ffffff";
	document.getElementById("precio2_I").style.backgroundColor = "#ffffff";
	document.getElementById("plazo2_I").style.backgroundColor = "#ffffff";
	document.getElementById("iva1_I").style.backgroundColor = "#ffffff";
	document.getElementById("final1_I").style.backgroundColor = "#ffffff";
	document.getElementById("iva2_I").style.backgroundColor = "#ffffff";
	document.getElementById("final2_I").style.backgroundColor = "#ffffff";
	document.getElementById("kiloVivo_I").style.backgroundColor = "#ffffff";
	document.getElementById("kiloCarne_I").style.backgroundColor = "#ffffff";
	document.getElementById("kiloVivo2_I").style.backgroundColor = "#ffffff";
	document.getElementById("kiloCarne2_I").style.backgroundColor = "#ffffff";
	document.getElementById("puesto_I").style.backgroundColor = "#ffffff";
	document.getElementById("comision_I").style.backgroundColor = "#ffffff";
	document.getElementById("fecha_I").style.backgroundColor = "#ffffff";
}

function editarTropaOrigen() //Enablea Informacion Origen
{
	document.getElementById("cantOrigen_I").disabled = false;
	document.getElementById("desb_I").disabled = false;
	document.getElementById("bruto_I").disabled = false;
	document.getElementById("neto_I").disabled = false;

	document.getElementById("cantOrigen_I").style.backgroundColor = "#ffffff";
	document.getElementById("desb_I").style.backgroundColor = "#ffffff";
	document.getElementById("bruto_I").style.backgroundColor = "#ffffff";
	document.getElementById("neto_I").style.backgroundColor = "#ffffff";
}

function editarTropaPlanta() //Enablea Informacion Planta
{
	document.getElementById("kgentrada_I").disabled = false;
	document.getElementById("kgcarne_I").disabled = false;
	document.getElementById("aclaracion_I").disabled = false;

	document.getElementById("kgentrada_I").style.backgroundColor = "#ffffff";
	document.getElementById("kgcarne_I").style.backgroundColor = "#ffffff";
	document.getElementById("aclaracion_I").style.backgroundColor = "#ffffff";
}

function cambiaEditValue() {
	document.formulario.edit_compfig.value="1";
}

function cambiaCancelValue() {
	document.formulario.edit_compfig.value="0";
}

function hide_edit(){
	document.getElementById("edit_tropa").style.display = "none";
	document.getElementById("cancel_tropa").style.display = "block";
}

function hide_cancel(){
	document.getElementById("edit_tropa").style.display = "block";
	document.getElementById("cancel_tropa").style.display = "none";
}

function hide_edit2(){
	document.getElementById("edit_tropa2").style.display = "none";
	document.getElementById("cancel_tropa2").style.display = "block";
}

function hide_cancel2(){
	document.getElementById("edit_tropa2").style.display = "block";
	document.getElementById("cancel_tropa2").style.display = "none";
}

function cancelarTropa() //Cancela la informacion del comprador, frigorifico, y precios/plazos/etc.
{
	document.getElementById("bmc").disabled = true;
	document.getElementById("bm").disabled = true;
	document.getElementById("bf").disabled = true;
	document.getElementById("precio1_I").disabled = true;
	document.getElementById("plazo1_I").disabled = true;
	document.getElementById("precio2_I").disabled = true;
	document.getElementById("plazo2_I").disabled = true;
	document.getElementById("iva1_I").disabled = true;
	document.getElementById("final1_I").disabled = true;
	document.getElementById("iva2_I").disabled = true;
	document.getElementById("final2_I").disabled = true;
	document.getElementById("kiloVivo_I").disabled = true;
	document.getElementById("kiloCarne_I").disabled = true;
	document.getElementById("kiloVivo2_I").disabled = true;
	document.getElementById("kiloCarne2_I").disabled = true;
	document.getElementById("puesto_I").disabled = true;
	document.getElementById("comision_I").disabled = true;
	document.getElementById("fecha_I").disabled = true;
	
	document.getElementById("bmc").style.backgroundColor = "#F2F2F2";
	document.getElementById("bm").style.backgroundColor = "#F2F2F2";
	document.getElementById("bf").style.backgroundColor = "#F2F2F2";
	document.getElementById("precio1_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("plazo1_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("precio2_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("plazo2_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("iva1_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("final1_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("iva2_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("final2_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("kiloVivo_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("kiloCarne_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("kiloVivo2_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("kiloCarne2_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("puesto_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("comision_I").style.backgroundColor = "#F2F2F2";
}

function cambiaEditValueOrigen() {
	document.formulario.edit_origen.value="1";
}

function cambiaCancelValueOrigen() {
	document.formulario.edit_origen.value="0";
}

function cambiaEditValuePlanta() {
	document.formulario.edit_planta.value="1";
}

function cambiaCancelValuePlanta() {
	document.formulario.edit_planta.value="0";
}

function cancelarTropaOrigen() //Cancela Informacion Origen
{
	document.getElementById("cantOrigen_I").disabled = true;
	document.getElementById("desb_I").disabled = true;
	document.getElementById("bruto_I").disabled = true;
	document.getElementById("neto_I").disabled = true;

	document.getElementById("cantOrigen_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("desb_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("bruto_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("neto_I").style.backgroundColor = "#F2F2F2";
}

function cancelarTropaPlanta() //Cancela Informacion Planta
{
	document.getElementById("kgentrada_I").disabled = true;
	document.getElementById("kgcarne_I").disabled = true;
	document.getElementById("aclaracion_I").disabled = true;

	document.getElementById("kgentrada_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("kgcarne_I").style.backgroundColor = "#F2F2F2";
	document.getElementById("aclaracion_I").style.backgroundColor = "#F2F2F2";
}

function refresh_multimedia(paramId)
{
	new posteoAjax('archivos_multimedia_negocio.php?perm=W','idnegocio='+paramId,'contenido-multimedia','1','1');
}



function refresh_multimedia_rom(paramId)
{
	new posteoAjax('archivos_multimedia_negocio.php?rom','tipo=2&idnegocio='+paramId,'contenido-multimedia-rom','1','1');
}

function refresh_multimedia_liq(paramId)
{
	new posteoAjax('archivos_multimedia_negocio.php?liq','tipo=3&idnegocio='+paramId,'contenido-multimedia-liq','1','1');
}

function refresh_multimedia_negocio_nuevo() //Refresh cuando se agrega un negocio nuevito (toma el ultimo id)
{
	new posteoAjax('archivos_multimedia_negocio.php','idnegocio=0','contenido-multimedia','1','1');
}

function estado_botones(numero)
{
	if(document.getElementById("estado_botones"))
	{
		if(numero == 0)
		{
			document.getElementById("estado_botones").value='0';
		}
		else if(numero == 1)
		{
			document.getElementById("estado_botones").value = '1';
		}
		else
		{
			return document.getElementById("estado_botones").value;
		}
	}
}

function convertir_usuario(t) {
	t.parentNode.style.display='none';
	document.getElementById('maill_M').style.display='';
	document.getElementById('maill_M').focus();
}
function enviar_informe(correo)
{
	var detalle_carga = document.getElementById('detalle_carga').value;
	
	ajax=objetoAjax();

	var cadenaFormulario = "detalle_carga=" + detalle_carga + "&correo=" + correo;

	if(confirm('Confirmar el envio a \"' + correo + '\"?') == false){return false;}
	
	ajax.open("POST", "lib/enviar_informe_carga.php", true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText == "1")
			{
				alert("Enviado");
			}
			else
			{							
				alert("No se pudo enviar el informe");
			}
		}
	}
	ajax.send(cadenaFormulario);
}

function representante_limpiar_campos()
{
	if(document.getElementById('id_representante')) {
		
	var id_representante = document.getElementById('id_representante');
	id_representante.value = "";
	id_representante.readOnly = true;
	
	var nombre_representante = document.getElementById('nombre_representante');
	nombre_representante.value = "";
	nombre_representante.readOnly = true;

	var ape_representante = document.getElementById('ape_representante');
	ape_representante.value = "";
	ape_representante.readOnly = true;
	
	var mail_representante = document.getElementById('mail_representante');
	mail_representante.value = "";
	mail_representante.readOnly = true;
	
	var telefono_representante = document.getElementById('telefono_representante');
	telefono_representante.value = "";
	telefono_representante.readOnly = true;
	
	var ubicacion_representante = document.getElementById('ubicacion_representante');
	ubicacion_representante.value = "";
	ubicacion_representante.readOnly = true;
	
	}
}

function cargar_motivo_filtro(valor)
{
	var Resultado;
	Resultado = document.getElementById('filtrados');
	ajax=objetoAjax();
	ajax.open("GET", "filtros_solicitud_admin.php?valor="+valor,true);
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText != "")
			{
				Resultado.innerHTML = ajax.responseText;	
			}
			else
			{										
				Resultado.innerHTML = ajax.responseText;
			}
		}
	}
	ajax.send(null);
}

function carga_datos_transporte(id)
{
	var cadena = "lib/bits.php?data_transporte&dato_transporte="+id;
	
	ajax=objetoAjax();
	ajax.open("GET", cadena,true);
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			Resultado = document.getElementById('detalles_transporte');
			
			if(ajax.responseText != "")
			{				
				Resultado.innerHTML= ajax.responseText;
			}
			else
			{
				Resultado.innerHTML = "No hay respuesta del archivo";
			}
		}
	}
	ajax.send(null);
}

function filtra_usuarios(variable,prov)
{	
	if(variable == "agenda") {var cadena = "filtro_busqueda_usuarios.php?Ea=1";}
	else if(variable == "enviar_lote" || variable=="enviar_lote_rep") {
		var cadena = "filtro_enviar_lote.php?lista=1";
		if(document.getElementById('cc_machos')) {
			if(document.getElementById('cc_machos').checked==true) {var mach = "on";}
			if(document.getElementById('cc_hembras').checked==true) {var hemb = "on";}
			if(document.getElementById('cc_machos_hembras').checked==true) {var myh = "on";}
			if(document.getElementById('cc_cria').checked==true) {var cria = "on";}
			if(document.getElementById('cc_compra').checked==true) {var compra = "on";}
			if(document.getElementById('cc_vende').checked==true) {var vende = "on";}
		}
	}

	else if(variable == "enviar_informe") {var cadena = "filtro_enviar_informe.php?Ea=1";} 

	var mail_registro = document.getElementById("mail_registro");
	var nombre = document.getElementById("nombre");
	var apellido = document.getElementById("apellido");
	var provincia = document.getElementById("provincia");

	var partido;
	
	if(variable=="enviar_lote_rep") {var cadena = "filtro_enviar_lote_rep.php?listas=1"}
	if(document.getElementById('tipo')) {if(document.getElementById('tipo').value=='sms'){cadena = "filtro_enviar_sms.php?lista=1";}}
	
	if(mail_registro)
	{
		if(mail_registro.value != '') {cadena += "&mail_registro=" + mail_registro.value;}
	}	
	if (nombre)
	{
		if (nombre.value != '') {cadena += "&nombre=" + nombre.value;}
	}	
	if(apellido)
	{
		if(apellido.value != '') {cadena += "&apellido=" + apellido.value;}
	}
	if(provincia)
	{
		if(provincia.value != '0') {cadena += "&provincia=" + provincia.value;if(prov!=1) {var partido = document.getElementById("partido");}}
		//if(provincia.value != '0') { cadena += "&provincia=" + provincia.value; var partido = document.getElementById("partido"); }
	}	
	if (partido)
	{
		if (partido != null) 
		{
			if (partido.value != '0') {cadena += "&partido=" + partido.value;}
		}
	}
	
	if(variable == "enviar_lote" || variable=="enviar_lote_rep") {
		cadena += "&cc_machos=" + mach + "&cc_hembras=" + hemb + "&cc_machos_hembras=" + myh + "&cc_cria=" + cria + "&cc_compra=" + compra + "&cc_vende=" + vende;
	}	

	if(estado_botones('11') == 0) {cadena += "&estado_botones=0";}

	ajax=objetoAjax();
	ajax.open("GET", cadena,true);
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText != "")
			{
				if(document.getElementById("filtrados"))
				{
					document.getElementById("filtrados").innerHTML = ajax.responseText;
					if(variable=="enviar_lote" || variable=="enviar_lote_rep") {act_boton();}
				}													
			}
			else
			{
				Resultado = document.getElementById('filtrados');
				if(Resultado) {Resultado.innerHTML = ajax.responseText;}
			}
		}
	}
	ajax.send(null);
}

// Agenda inicio

function agenda_agregar_contacto()
{
	
	var nombre = document.getElementById("nombre").value;
	var apellido = document.getElementById("apellido").value;

	parent.Shadowbox.open
	({
		content:    'lib/guardar_contacto_agenda.php?nombre=' + nombre + '&apellido=' + apellido,
		player:     'iframe',
		height:     270,
		width:      440
	});
}

function agenda_form_agregar_llamado()
{
	var agr = document.getElementById("agr");
	var respuesta = "";
	ajax=objetoAjax();
	ajax.open("GET", "fragmentos/agenda_agregar_llamado.php",true);	
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) 
		{
			agr.innerHTML = ajax.responseText;
			new Effect.Appear(agr, {duration: 0.35} );
			document.getElementById('telefonito').style.backgroundImage = "url('imagenes/telefono_agenda_off.jpg')";
			document.getElementById('telefonito').onclick = function() {eval("agenda_form_cancelar_llamado()");}
			fecha = document.getElementById('fecha_i');
			new Control.DatePicker(fecha, {icon: '/cal/calendar.png', timePicker: true, dateTimeFormat: 'yyyy-MM-dd HH:mm:00'});
		}	
	}
	ajax.send(null)
}
function agenda_form_cancelar_llamado()
{
	var agr = document.getElementById("agr");
	new Effect.Fade(agr, {duration: 0.15});
	setTimeout("agr.innerHTML = '';",150);
	document.getElementById('telefonito').style.backgroundImage = "url('imagenes/telefono_agenda.jpg')";
	document.getElementById('telefonito').onclick = function() {eval("agenda_form_agregar_llamado()");}
}

function agenda_seleccionar_usuario()
{	
		Shadowbox.open
		({
	        content:    'buscador_popup.php',
	        player:     "iframe",
	        height:     453,
	        width:      730
	    });
}

function agenda_seleccionar(nom_ape, usuario, tipo)
{
	document.getElementById('nom_ape').innerHTML = nom_ape;
	document.getElementById('usuario').value = usuario;
	document.getElementById('tipo').value = tipo;
	Shadowbox.close();
}

function agenda_guardar_llamado_check()
{
	var usuario = document.getElementById('usuario').value;
	var tipo = document.getElementById('tipo').value;
	var comunicacion_con = document.getElementById('comunicacion_con').value;
	var motivo = document.getElementById('motivo').value;
	
	var error = "";
	
	if(usuario == "")
	{
		error += "No se ha seleccionado el usuario\n";
	}
	
	if(comunicacion_con == "0")
	{
		error += "No se ha seleccionado el destinatario\n";
	}
	
	if(motivo == "")
	{
		error += "Debe especificar el motivo del llamado\n";
	}
	
	if(error != "")
	{
		alert(error);
	}
	else
	{
		return true;
	}
}

function agenda_check_guardar()
{
	if(agenda_guardar_llamado_check())
	{
		agenda_guardar_llamado();
	}
}

function agenda_guardar_llamado()
{
	var usuario = document.getElementById('usuario').value;
	var tipo = document.getElementById('tipo').value;
	var comunicacion_con = document.getElementById('comunicacion_con').value;
	var motivo = document.getElementById('motivo').value;	
	var fecha = document.getElementById('fecha_i').value;	
	
	ajax=objetoAjax();

	var cadenaFormulario = "usuario=" + usuario + "&tipo=" + tipo + "&comunicacion_con=" + comunicacion_con + "&motivo=" + motivo + "&fecha=" + fecha;

	ajax.open("POST", "lib/guardar_historial_agenda.php", true);	
	
	ajax.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=utf-8');
	
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText == "1")
			{
				window.location.href = window.location.href;				
			}
			else
			{							
				alert("no responde");
			}
		}
	}
	ajax.send(cadenaFormulario);
		
}	
//FINNNNN agenda_guardar_llamado

function envio_lote_agr_correo()
{
	var correo_externo = document.getElementById("correo_externo");	

	if(document.getElementById('tipo')) {if(document.getElementById('tipo').value=='sms'){agrega_usuario_a_lista(correo_externo.value, "(n�mero externo)", "");return false}}
	
	if(correo_externo.value!=" Agregar Nuevo.." && correo_externo.value!="")
	{
		if(valcorreo(correo_externo.value))
		{
			agrega_usuario_a_lista(correo_externo.value, "(Correo externo)", "");
			correo_externo.value = " Agregar Nuevo..";
		}
		else
		{
			correo_externo.focus();
		}
	}
}

function valcorreo(valor) {
	if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/.test(valor))
	{
		return (true)
	}
	else
	{
		alert("el correo " + valor + " es invalido");
		return false;
	}
}
function agrega_usu(id, apellido, nombre)
{
	if(!document.getElementById("div_" + id))
	{
		document.getElementById("usuarios_agregados").appendChild(crear_div(id, apellido, nombre));

		if(document.getElementById(id)){
			var yo = document.getElementById(id);yo.className="ico_disa";
			yo.setAttribute("onclick", "remover_de_lista('" + id +"','"+ apellido +"','"+ nombre +"')");
		}
	}
}
function agrega_usuario_a_lista(id, apellido, nombre)
{
	if(!document.getElementById("div_" + id))
	{		
		if(document.getElementById("usuarios_agregados").innerHTML=="") {
			document.getElementById("usuarios_agregados").appendChild(crear_div(id, apellido, nombre));
		}
		else
		{
			primer_div = document.getElementById("usuarios_agregados").getElementsByTagName("div");
			primer_div[0].parentNode.insertBefore(crear_div(id, apellido, nombre),primer_div[0]);
		}
		if(document.getElementById(id)){
			var yo = document.getElementById(id);yo.className="ico_disa";
			yo.setAttribute("onclick", "remover_de_lista('" + id +"','"+ apellido +"','"+ nombre +"')");
			new Effect.Highlight(document.getElementById("div_" + id), {startcolor: '#C8EEBD', endcolor: '#F1F7F0'})
		}
	}
}
function crear_div(id, apellido, nombre)
{
	var div_principal = document.createElement("div");
		div_principal.innerHTML = '<div id="div_'+id+'" class="a_enviar"><div><button name="'+id+'" title="Quitar" onclick="remover_de_lista(\''+id+'\',\''+apellido+'\',\''+nombre+'\');">x</button></div><span>'+nombre+' '+apellido+'</span><br /><span class="blue">'+id+'</span><input name="usuarios[]" type="hidden" value="'+id+'"></div>';
		return div_principal;
}

function remover_de_lista(id, apellido, nombre)
{
	if(document.getElementById("div_"+id))
	{
		var nodo = document.getElementById("div_"+id);
		nodo.parentNode.removeChild(nodo);
	
		if(document.getElementById(id))
		{
			var yo = document.getElementById(id);
			yo.className="ico_able";
			yo.setAttribute("onclick", "agrega_usuario_a_lista('" + id +"','"+ apellido +"','"+ nombre +"')");
		}
	}
}

function act_boton() {
	
	if(document.getElementById('usuarios_agregados')){
		
	var aenviar = document.getElementById('usuarios_agregados').getElementsByTagName('input');
	var filtrados = document.getElementById('filtrados').getElementsByTagName('input');
	var cont = botones = 0;
	
	for (var i=0; i < aenviar.length; i++) 
	{
		for (var j=0; j < filtrados.length; j++) 
		{
			if( i==0 && filtrados[j].type == "button") {botones++;}
			
			if(filtrados[j].getAttribute("id")!=null && aenviar[i].value!=null) {
				if(aenviar[i].value==filtrados[j].getAttribute("id")) {
					filtrados[j].className="ico_disa";
					clickeo = filtrados[j].getAttribute("onclick");
					clickeo = clickeo.replace('agrega_usuario_a_lista','remover_de_lista');
					filtrados[j].setAttribute("onclick",clickeo);
					cont++
				}
			}
		}
	}
	if(cont==botones && cont!=0)
	{
		var t = document.getElementById('select');
		t.checked = 1;t.setAttribute("title","Seleccionar Ninguno");
		t.setAttribute("onclick","sel_nin()");
	}
	return false;
	}
}

function sel_todos(param) {

	var filtrados = document.getElementById('filtrados').getElementsByTagName('input');

	for (var i=0; i < filtrados.length; i++)
	{
		if(filtrados[i].getAttribute("onclick")) {var acc = filtrados[i].getAttribute("onclick");}
		else {acc="";}
		
		busc = /agrega_usu/g;acc = acc.replace('agrega_usuario_a_lista','agrega_usu');
		if(busc.test(acc) && acc!="") {eval(acc);}
	}
	var t = document.getElementById('select');
	t.checked = 1;t.setAttribute("title","Seleccionar Ninguno");
	if(!param) {
		t.setAttribute("onclick","sel_nin()");
	}
	else
	{		
		t.setAttribute("onclick","sel_nin(1)");
	}
//	return false;
}

function sel_nin(param) {
	
	if(document.getElementById('usuarios_agregados')){
		
	var aenviar = document.getElementById('usuarios_agregados').getElementsByTagName('input');
	var filtrados = document.getElementById('filtrados').getElementsByTagName('input');

	for (var i=0; i < filtrados.length; i++) 
	{
		if(filtrados[i].getAttribute("id")!=null) {
			var acc = filtrados[i].getAttribute("onclick");	
			busc = /remov/g;
			if(busc.test(acc) && acc!="") {remover_de_lista(filtrados[i].getAttribute("id"));}
		}
	}
	var t = document.getElementById('select');
	t.setAttribute("onclick","sel_todos()");
	if(!param) {
		filtra_usuarios('enviar_lote');
	}
	else
	{	
		filtra_usuarios('enviar_lote_rep');
	}
	}
}

function sel_todos_envio_mails()
{
	var Formulario = document.getElementById('usuarios_agregados').getElementsByTagName('input');

	for (var i=0; i <= Formulario.length-1;i++) {Formulario[i].checked=true;}

	document.getElementById('enviar_lote_mail').removeAttribute('disabled');
}

function enviar_formulario_mensajes(param)
{
	if(document.getElementById("reenvio") && document.getElementById("reenvio").value == 1)
	{
		if(!param) {return reenviar_formulario_mensajes();} else {return reenviar_formulario_mensajes(1);}
	}

	var cadenaFormulario = "";
	var contenedor = document.getElementById('usuarios_agregados');
	var Formulario = contenedor.getElementsByTagName('input');

	if(param=='todos')
 	{
		if(confirm('Desea agregar a la cola de envio a toda la base de datos?') == false){
			return false;
		}
		else
		{
			cadenaFormulario = "enviar_a_todos=1";
		}
 	}
	else if(param=='todos_si')
	{
		cadenaFormulario = "dije_a_todos=1";
	}
	else
	{
		var sepCampos;sepCampos = "";

		for (var i=0; i <= Formulario.length-1;i++) 
		{
			cadenaFormulario += sepCampos+Formulario[i].name+'='+encodeURI(Formulario[i].value);
			sepCampos="&";
		}
		if(document.getElementById('mensaje_sms')) {cadenaFormulario += '&mensaje='+document.getElementById('mensaje_sms').value;}
	}

	ajax=objetoAjax();

	if(document.getElementById('tipo'))
	{
		if(document.getElementById('tipo').value=='sms')
		{
			ajax.open("POST", 'sms/envios_lote_sms.php', true);
		}
		else
		{
			ajax.open("POST", 'guardar_mensajes.php', true);
		}
	}
	else
	{
		ajax.open("POST", 'guardar_mensajes.php', true);
	}

	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText != "")
			{
				contenedor.innerHTML = ajax.responseText;
				estado_botones(0);
				document.getElementById("agr_us").setAttribute("disabled", "true");
				document.getElementById("correo_externo").setAttribute("disabled", "true");
				document.getElementById("enviar_lote_mail").setAttribute("disabled", "true");
				if(!param) {filtra_usuarios('enviar_lote');}
				
			}
			else
			{
				contenedor.innerHTML = "<h5>No hay respuesta</h5>";
			}
		}
	}
	ajax.send(cadenaFormulario);
}

function agregar_mas_usuarios_mail(param)
{
	var nodo = document.getElementById("usuarios_agregados");
	nodo.parentNode.removeChild(nodo);
	
	var formulario = document.createElement("form");
		formulario.setAttribute("id", "usuarios_agregados");
		document.getElementById("usuarios_agregados_cont").appendChild(formulario);
		document.getElementById("enviar_lote_mail").removeAttribute("disabled");
		document.getElementById("agr_us").removeAttribute("disabled");
		document.getElementById("correo_externo").removeAttribute("disabled");
		estado_botones(1);
		if(!param) {filtra_usuarios('enviar_lote');}
}

function reenviar_formulario_mensajes(param)
{
	var Formulario = document.getElementById('usuarios_agregados');
	var cadenaFormulario = "";
	var sepCampos;sepCampos = "";

	for (var i=0; i <= Formulario.elements.length-1;i++)
	{
		if(Formulario.elements[i].checked==true)
		{
			cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+encodeURI(Formulario.elements[i].value);
			sepCampos="&";
		}
	}
	if(document.getElementById('mensaje_sms')) {cadenaFormulario += '&mensaje='+document.getElementById('mensaje_sms').value;}

	ajax=objetoAjax();

	if(document.getElementById('tipo'))
	{
		if(document.getElementById('tipo').value=='sms')
		{
			ajax.open("POST", 'sms/envios_lote_sms.php?nocheck', true);
		}
		else
		{
			ajax.open("POST", 'guardar_mensajes.php?nocheck', true);
		}
	}
	else
	{
		ajax.open("POST", 'guardar_mensajes.php?nocheck', true);
	}

	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText != "")
			{
				Formulario.innerHTML = ajax.responseText;
				estado_botones(0);
				document.getElementById("enviar_lote_mail").setAttribute("disabled", "true");
			 	document.getElementById("agr_us").setAttribute("disabled", "true");
				document.getElementById("correo_externo").setAttribute("disabled", "true");
				if(!param) {filtra_usuarios('enviar_lote');}
			}
			else
			{							
				Formulario.innerHTML = "<h5>No hay respuesta</h5>";
			}
		}
	}
	ajax.send(cadenaFormulario);
}


function ajax_completar_representante(id)
{
	var Resultado;
		Resultado = document.getElementById("rep_asignado");
	var cadena = "listado_representantes.php?rep=" +id;
	ajax=objetoAjax();
	ajax.open("GET", cadena,true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			Resultado.innerHTML = ajax.responseText;								
		}
	}
	ajax.send(null);
	return;
}

function cli_a_rep(cliente)
{
	if(confirm('Confirma el cambio de perfil del usuario #' + cliente + ' a representante? \n\n ESTE CAMBIO NO SE PODRA REVERTIR') == false){return false;}
	
	var Resultado;
	Resultado = document.getElementById('establecer_cliente_representante');
	ajax=objetoAjax();
	ajax.open("GET", "lib/cliente_a_representante.php?cliente="+cliente,true);
	ajax.onreadystatechange=function()
	{

		if (ajax.readyState==4) 
		{
			if(ajax.responseText != "")
			{
				alert(ajax.responseText);
				window.location.href = window.location.href;
				return false;
			}
			else
			{										
				Resultado.innerHTML = ajax.responseText;
			}
		}
	}
	ajax.send(null);
}

function ajax_telefonos_senasa(val,id_prov)
{
	var Resultado;
		Resultado = document.getElementById("telefono_senasa_"+val);
		
	var cadena = "telefonos_senasa.php?id_provincia="+id_prov+"&val="+val;
		ajax=objetoAjax();
		ajax.open("GET", cadena,true);
		ajax.onreadystatechange = function()
		{
			if (ajax.readyState == 4)
			{
					document.getElementById("telefono_senasa_"+val).innerHTML = ajax.responseText;								
			}
		}
		ajax.send(null);
	return;
}

function ajax_buscador_cliente()
{
	var Resultado;
		Resultado = document.getElementById("coincidencias");
	
	var nombre = document.getElementById("nombre").value;

	if(nombre.length > 2)
	{
		var cadena = "fragmentos/buscador_org.php?nombre="+ nombre;
		ajax=objetoAjax();
		ajax.open("GET", cadena,true);
		ajax.onreadystatechange = function()
		{
			if (ajax.readyState == 4)
			{
					Resultado.innerHTML = ajax.responseText;
			}
		}
		ajax.send(null);
	}
}

function ajax_buscador_usuarios()
{
	var Resultado;
		Resultado = document.getElementById("coincidencias");
	
	var nombre = document.getElementById("nombre").value;
	var apellido = document.getElementById("apellido").value;
	var razon_social = document.getElementById("razon_social").value;

	var tutti = nombre.length + apellido.length + razon_social.length;

	if(tutti > 2 )
	{
		var cadena = "fragmentos/buscador_usuarios.php?nombre="+ nombre +"&apellido="+apellido + "&razon_social="+ razon_social;
		ajax=objetoAjax();
		ajax.open("GET", cadena,true);
		ajax.onreadystatechange = function()
		{
			if (ajax.readyState == 4)
			{
					Resultado.innerHTML = ajax.responseText;
					document.getElementById("div_establecimientos").innerHTML = '<input type="hidden" id="establecimiento" name="establecimiento" value="" />';
			}
		}
		ajax.send(null);
	}
	else
	{
		Resultado.innerHTML = '<input type="hidden" id="clienteid" name="clienteid" value="" />';
		document.getElementById("div_establecimientos").innerHTML = '<input type="hidden" id="establecimiento" name="establecimiento" value="" />';
	}
	return;
}

function ajax_buscar_establecimientos(cliente,n,a,r)
{
	var campo_n = document.getElementById("nombre");
	var campo_a = document.getElementById("apellido");
	var campo_r = document.getElementById("razon_social");	

	var n_antes = document.getElementById("n").value;
	var a_antes = document.getElementById("a").value;
	var r_antes = document.getElementById("r").value;

	campo_n.value = n;campo_a.value = a;campo_r.value = r;

	campo_n.onfocus = campo_a.onfocus = function()
	{
		campo_n.value  = n_antes;campo_a.value = a_antes;campo_r.value = r_antes;
	}

	var cadena = "fragmentos/establecimientos_cliente.php?cliente="+cliente;
		ajax=objetoAjax();
		ajax.open("GET", cadena,true);
		ajax.onreadystatechange = function()
		{
			if (ajax.readyState == 4)
			{
					document.getElementById("div_establecimientos").innerHTML = ajax.responseText;								
			}
		}
		ajax.send(null);
	return;	
}

function nc_estab(n)
{
	estab = document.getElementById("capa_nuevo_establecimiento");
	
	if(n=='NUEVO') {
		estab.style.display = "";
		document.getElementById("establecimiento_nuevo_I").style.display = "";
		document.getElementById("provincia_I").style.display = "";
		document.getElementById("partido_I").style.display = "";
	}
	else {
		estab.style.display = "none";
		document.getElementById("establecimiento_nuevo_I").style.display = "none";
		document.getElementById("provincia_I").style.display = "none";
		document.getElementById("partido_I").style.display = "none";
	}
}

function stateChanged_p_negocio_cerrado_cliente()
{
   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
   {
		   document.getElementById("partidos_est_nuevo").innerHTML= xmlHttp.responseText;
   }
   else {}
}

function partidos_negocio_cerrado_cliente(url, qStr)
{
   if (url.length==0)
   {
       document.getElementById("partidos_est_nuevo").innerHTML="";
       return;
   }
   xmlHttp=GetXmlHttpObject()
   if (xmlHttp==null)
   {
       alert ("Browser does not support HTTP Request");
       return;
   }

   url=url+"?"+qStr;
   url=url+"&sid="+Math.random();
   xmlHttp.onreadystatechange=stateChanged_p_negocio_cerrado_cliente;
   xmlHttp.open("GET",url,true);
   xmlHttp.send(null);   
}
function ver_interesado_n(rev,cli)
{
		Shadowbox.open
		({
	        content:    'resultado_negociacion.php?revisacion='+rev+'&cliente='+cli,
	        player:     "iframe",
	        width:      "460"
	    });
}
function tab_usu(sec,cli,t) {
	
	if(document.getElementById("advert")) {
		var adv = document.getElementById("advert");	
		if(cli=="") {adv.style.display = "";adv.innerHTML = "No se encuentra el usuario, falta ID";return false;}
		else {adv.style.display = "none";}
	}
	
	var a = $$('.menu_h a');
	for(var i=0;i<a.length; i++) {
		a[i].className = "";
	}
	var ver = document.getElementById('ver_usu');
	var cambio = document.getElementById('cambio');
	ver.style.display="none";

	if(t) { 
		var divs = document.getElementById("tabs").getElementsByTagName("div");
		for(var i=0;i<divs.length; i++) {
			divs[i].className = "";
		}
		t.parentNode.className = "active";
	}
	
	if(sec=="ver") {
		ver.style.display="";cambio.style.display="none";
	}
	else
	{
		cambio.style.display="";ver.style.display="none";
		
		var url = "fragmentos/usuario/"+sec+".php?usuario="+cli;
		ajax=objetoAjax();ajax.open("GET", url, true);
		ajax.onreadystatechange = function()
		{
			if (ajax.readyState == 4) {cambio.innerHTML = ajax.responseText;}
		}
		ajax.send(null);
		return;
	}
}

function cc(t) {
	linea = t.parentNode.parentNode;
	radios = linea.getElementsByTagName('input');
	if(linea.className=='cruz'){
		for(i=0; i<radios.length; i++) {radios[i].className='';}
	}
	if(t.className=='marc') {t.className=''} else {t.className='marc'}
}

function guardar_criterios(cli)
{
	var form = "guardar_criterios=si";
	var cambio = document.getElementById('cambio');
	if(document.getElementById('cc_machos').checked==true) {var mach = "on";}
	if(document.getElementById('cc_hembras').checked==true) {var hemb = "on";}
	if(document.getElementById('cc_machos_hembras').checked==true) {var myh = "on";}
	if(document.getElementById('cc_cria').checked==true) {var cria = "on";}
	if(document.getElementById('compra').checked==true) {var compra = "on";}
	if(document.getElementById('vende').checked==true) {var vende = "on";}
	
	var form = form + "&cc_machos=" + mach + "&cc_hembras=" + hemb + "&cc_machos_hembras=" + myh + "&cc_cria=" + cria + "&cc_compra=" + compra + "&cc_vende=" + vende;
	var url = "fragmentos/usuario/criterio.php?usuario="+cli;
	
	ajax=objetoAjax();ajax.open("POST", url, true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState == 4) {cambio.innerHTML = ajax.responseText;}
	}
	ajax.send(form);
}
function guardar_criterios2(cli)
{
	var form = "guardar_criterios=si";
	var cambio = document.getElementById('cambio');
	if(document.getElementById('cc_machos').className=="marc") {var mach = "on";}
	if(document.getElementById('cc_hembras').className=="marc") {var hemb = "on";}
	if(document.getElementById('cc_machos_hembras').className=="marc") {var myh = "on";}
	if(document.getElementById('cc_cria').className=="marc") {var cria = "on";}
	if(document.getElementById('compra').className=="marc") {var compra = "on";}
	if(document.getElementById('vende').className=="marc") {var vende = "on";}
	
	var form = form + "&cc_machos=" + mach + "&cc_hembras=" + hemb + "&cc_machos_hembras=" + myh + "&cc_cria=" + cria + "&cc_compra=" + compra + "&cc_vende=" + vende;
	var url = "fragmentos/usuario/criterio.php?usuario="+cli;
	
	ajax=objetoAjax();ajax.open("POST", url, true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState == 4) {cambio.innerHTML = ajax.responseText;}
	}
	ajax.send(form);
}

function tab_envio(tabeable,t)
{	

	var tipo = document.filtro.tipo;
	tipo.value = tabeable;
	document.getElementById('ext_text').innerHTML = tabeable+ " externo";
	tt = document.getElementById('tt');
	
	if(tabeable=='sms')
	{
		tt.style.display = 'none';
		document.getElementById('contenido_sms').style.display = '';
	}
	else
	{
		tt.style.display = '';
		document.getElementById('contenido_sms').style.display = 'none';
	}
	
	var tabs = document.getElementById("tabs").getElementsByTagName("div");
	for(var i=0;i<tabs.length; i++) {
		if(tabs[i].className!="ader") {tabs[i].className = "";}
	}
	t.parentNode.className = "active";
	agregar_mas_usuarios_mail();
	filtra_usuarios('enviar_lote');
}

function tab_esta(secc,t) {	

	le = document.getElementById('listado');
	le.innerHTML = '<div class="acen top30"><img class="top30" src="imagenes/ajax-loader_video.gif" /></div>';
	var url = "estadisticas/listados_lotes.php?" + secc;
	ajax=objetoAjax();ajax.open("GET", url,true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4) {le.innerHTML = ajax.responseText;}
	}
	ajax.send(null);

	if(t)
	{
		var tabs = document.getElementById("tabs_esta").getElementsByTagName("div");
		for(var i=0;i<tabs.length; i++) {
			tabs[i].className = "";
		}
		t.parentNode.className = "active";
	}
}

function nc_tab(tipo,t) {
	
	var exist = document.getElementById("exist");
	var nuevo = document.getElementById("nuevo");
	var repre = document.getElementById("repre");
	
	exist.style.display = nuevo.style.display = repre.style.display = "none";
	
	if(tipo == "exist") {exist.style.display = "";}
	if(tipo == "nuevo") {nuevo.style.display = "";}
	if(tipo == "repre") {repre.style.display = "";}

	var divs = document.getElementById("tabs").getElementsByTagName("div");
	for(var i=0;i<divs.length; i++) {
		divs[i].className = "";
	}
	t.parentNode.className = "active";	
}

var rand=35691;
function firm(saca,eee) {
	firmas = document.getElementById('firmas');
	sacar = document.getElementById(saca);
	rand++;

	if(saca=="+") {
		otro = document.createElement("span");
		otro.setAttribute("id",rand);
		if(eee)
		{
			otro.innerHTML =
				'<b>Nombre</b><input type="text" name="firma[]" id="_I" /> <button class="transpa" onclick="firm('+rand+')">Borrar</button>';
		}
		else
		{
			otro.innerHTML =
				'<input type="text" name="firma[]" id="_I" /> <button class="transpa" onclick="firm('+rand+')">x</button>';
		}
		firmas.appendChild(otro);
		otro.getElementsByTagName("input")[0].focus();
	}
	else
	{
		sacar.parentNode.removeChild(sacar);
	}
}

function pers(saca) {
	personas = document.getElementById('personas');
	sacar = document.getElementById(saca);
	rand++;

	if(saca=="+") {
		otro = document.createElement("span");
		otro.setAttribute("id",rand);
		otro.innerHTML =
		'<div><b>Nombre</b><input type="text" name="pnombre[]" id="_I" /></div><div><b>Telefono</b>' +
		'<input type="text" name="ptelefono[]" id="_I" /></div><div class="ader editare"><a href="#" onclick="pers('+rand+'); return false">Borrar</a></div>';	
		personas.appendChild(otro);
		otro.getElementsByTagName("input")[0].focus();
	}
	else
	{
		sacar.parentNode.removeChild(sacar);
	}
}

function ordenou(que) {posteoAjax('estadisticas/listado_destinatarios.php' + que,document.filt);}

function buscar_lista(e,b,target,donde)
{        
    
    
        
	if(window.event) {k = e.keyCode} else if(e.which) {k = e.which}

	as = $(target).getElementsByTagName("a");

	b.setAttribute('onkeypress','return noenter(event)');
	b.setAttribute("onblur","$('"+target+"').fade({ duration: 0.20 })");
	
	
   
	$(target).observe('mouseover', function() {
		if($(this).up().down('.selec')) $(this).up().down('.selec').removeClassName('selec');
	});
	
	

	if(as)
	{
		for(i=0; as.length>i; i++) {if(as[i].className=='selec') {sel = i;}as[i].className ='';}
                
		if(k==40) // si key es down:
		{
			if((sel+1)<as.length)
			{
				as[sel+1].className = 'selec';
			}
			else
			{
				as[0].className = 'selec';
			}
			return false;
		}
		else if(k==38) // si key es up
		{
			if(sel>0)
			{
				as[sel-1].className = 'selec';
			}
			else
			{
				as[as.length-1].className = 'selec';
			}
			return false;
		}
		else if(k==13) // si key es enter:
		{
			if(as[sel].onclick)
			{
				as[sel].onclick();
				b.value = as[sel].innerHTML.replace(/&amp;/g,'&');
				$(target).fade({duration: 0.20}); 
				
			}
			else
			{
				window.open(as[sel].href);
			}
			return  false;
		}
	}
	if(b.value.length>0)
	{
		$(target).show();
		posteoAjax(donde,'b='+b.value,target,'1','1');
		
	
	}
}

function noenter(e) {
	if(window.event)
	{
		k = e.keyCode;
	}
	else if(e.which)
	{
		k = e.which;
	}
	return !(k == 13 || k == 40 || k == 38);
}

function krem(/*evento*/ e, /*formulario*/ f) 
{
	var k;var sel_i;var fg;
	var inp = document.getElementById('rem');
	if(!e) {inp.focus();inp.value=" ";posteoAjax('estadisticas/rem_inter.php?grafico',document.form_rem,'rem_main');return false}
	if(e=='f') { 
		if(document.form_rem.consulta_buscar_lotes_remitente.value!='' && document.form_rem.lote.value=='') {
			posteoAjax('estadisticas/rem_inter.php?lotes',document.form_rem,'rem_lotes');
		}
		posteoAjax('estadisticas/rem_inter.php?grafico',document.form_rem,'rem_main');
		return false;
	}
	document.form_rem.lote.value = '';
	var rems_div = document.getElementById('rems'); //resultado del query
	var sel = document.getElementsByClassName("rem_sel",rems_div)[0];
	if(sel) {f.consulta_buscar_lotes_remitente.value = sel.getAttribute('id');}
	var rems = rems_div.getElementsByTagName('div');

	if(window.event) {k = e.keyCode} else if(e.which) {k = e.which}

if(rems_div.style.display!='none')
{
	for(i=0; rems.length>i; i++) {if(rems[i].className=='rem_sel') {sel_i = i;}rems[i].className ='';} // le saco el estido a todos y veo cual es el selec

	if(k==40) // si key es down:
	{
		if(sel && sel_i!=(rems.length-1)) {next = parseInt(sel_i) + 1} else {next = 0} // si hay algun selec y no es el ultimo, selec el prox sino el primero.	
		rems[next].className = 'rem_sel';f.consulta_buscar_lotes_remitente.value = rems[next].getAttribute('id');// asigno estilo. el input toma el valor del selec y corta
		return false;
	}
	else if(k==38) // si key es up - hago todo lo mismo que antes pero a la inversa.
	{
		if(sel && sel_i!=0) {bef = parseInt(sel_i) - 1} else {bef = rems.length - 1}
		rems[bef].className = 'rem_sel';f.consulta_buscar_lotes_remitente.value = rems[bef].getAttribute('id');
		return false;
	}
	else if(k==13) // si key es enter:
	{
		if(!sel) {alert('seleccione un representante');inp.focus();}
		else {
			posteoAjax('estadisticas/rem_inter.php?lotes',document.form_rem,'rem_lotes');
			posteoAjax('estadisticas/rem_inter.php?grafico',document.form_rem,'rem_main');
			rems_div.style.display = 'none';
		}
	}
	else if(k==9 || k==27) {rems_div.style.display = 'none';return false;}
	else {posteoAjax('estadisticas/rem_inter.php?rems',f,'rems');}
}
else
{
	posteoAjax('estadisticas/rem_inter.php?rems',f,'rems');
	rems_div.style.display = 'block';
}
}
function stat_rem(acc,t,r) {
	
	var rems_div = document.getElementById('rems'); //resultado del query

	if(acc==1){
		t.getElementsByTagName("div")[0].className = 'rem_sel';
		t.setAttribute("onmouseout", "stat_rem(2,this)");
	}
	else if(acc==2){
		t.getElementsByTagName("div")[0].className = '';
	}
	else {
		document.form_rem.consulta_buscar_lotes_remitente.value = r;rems_div.style.display = 'none';
		posteoAjax('estadisticas/rem_inter.php?lotes',document.form_rem,'rem_lotes');
		posteoAjax('estadisticas/rem_inter.php?grafico',document.form_rem,'rem_main');
	}
}
function stat_reml(lote) {
		document.form_rem.lote.value = lote;
		posteoAjax('estadisticas/rem_inter.php?grafico',document.form_rem,'rem_main');
}

function armar_newsletter(form) {

	var cambio = parent.document.getElementById("cambio");
	var formm = parent.document.nl;

	var post = generoQuery(form);
	var postm = generoQuery(formm);

	ajax=objetoAjax();ajax.open("POST", "nl/armar.php", true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');

	ajax.onreadystatechange=function()
	{
		if (ajax.readyState == 4) {cambio.innerHTML = ajax.responseText;parent.Shadowbox.close();}
	}
	ajax.send(post+postm);
}
function mail_nl(saca) {
	firmas = document.getElementById('mails_nl');
	sacar = document.getElementById(saca);
	rand++;

	if(saca=="+") {
		otro = document.createElement("span");
		otro.setAttribute("id",rand);
		otro.innerHTML = '<input type="text" name="mail_nl[]" id="_MV" /> <a href="#" onclick="mail_nl('+rand+'); comp(\'formu\'); return false;">borrar</a>';
		firmas.appendChild(otro);
		otro.getElementsByTagName("input")[0].focus();
	}
	else
	{
		sacar.parentNode.removeChild(sacar);
	}
}
function add_cb(saca) {
	cuentas = document.getElementById('cuentas');
	sacar = document.getElementById(saca);
	rand++;

	if(saca=="+") {
		otro = document.createElement("span");
		otro.setAttribute("id",rand);
		agregado = '<input type="hidden" name="cuenta[]" value="nueva" />';
		agregado+= '<div><b>Banco</b><input type="text" name="banco[]" id="_I" /></div>';
		agregado+= '<div><b>Tipo</b><input type="text" name="tipo[]" id="_I" /></div>';
		agregado+= '<div><b>N&uacute;mero</b><input type="text" name="numero[]" id="_I" /></div>';
		agregado+= '<div><b>CBU</b><input type="text" name="cbu[]" id="_I" /></div>';
		agregado+= '<div class="top5 ader editare"><a href="#" onclick="add_cb(\''+rand+'\'); return false">Borrar cuenta</a></div>';
		agregado+= '<div class="top10 bottom15"></div>';
		otro.innerHTML = agregado;
		cuentas.appendChild(otro);
		otro.getElementsByTagName("input")[1].focus(); // por el hidden, si no cambiar a cero [0]..
	}
	else
	{
		sacar.parentNode.removeChild(sacar);
	}
}
function add_est(saca) {
	estabs = document.getElementById('estabs');
	sacar = document.getElementById(saca);
	rand++;

	if(saca=="+") {
		otro = document.createElement("span");
		otro.setAttribute("id",rand);

		ajax = objetoAjax();ajax.open("POST", "fragmentos/usuario/estable_edit.php", true);
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
		ajax.onreadystatechange=function()
		{
			if (ajax.readyState == 4) {otro.innerHTML = ajax.responseText;otro.getElementsByTagName("input")[1].focus();}
		}
		ajax.send("rand="+rand);

		estabs.appendChild(otro);
	}
	else
	{
		sacar.parentNode.removeChild(sacar);
	}
}
function cargar_stat_nl(/*post*/ p, /*target*/t, thi)
{
	var target = document.getElementById(t);
 
	if(target.style.display=='block')
	{
		target.style.display = 'none';
		target.innerHTML = '';
		thi.style.backgroundColor = '#E6E6E6';
	}
	else
	{
		posteoAjax('nl/graf_stat.php',p,t,'1');
		target.style.display = 'block';
		thi.style.backgroundColor = '#BCD4EF';
	}
}
function loteA(rev)
{
	var hacer = "var so = new SWFObject('p/pl.swf','mpl','428','320','0'); so.addParam('allowfullscreen','true'); so.addParam('allowscriptaccess','always'); so.addParam('wmode','opaque'); so.addParam('flashvars','skin=p/bekle.swf&lightcolor=3678B4&autostart=true&controlbar=over&stretching=fill&file=../videos/"+rev+".flv'); so.write('video'); new Carousel($('fotos_lote').down('.middle'), $('fotos_lote').down('.inner').select('img'), $('control').select('a'), { duration: 0.4, circular: true });";
	new posteoAjax('index.php?ver_lote='+rev,'cargarAjax=l','contenido','1','1',hacer);
}
// EVITAR TAB EN TEXTAREA y se usa as� -> onkeydown="return interceptTabs(event, this)"

function insertAtCursor(myField, myValue)
{
//IE support
if (document.selection)
    {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
    }

//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0')
    {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    restoreTop = myField.scrollTop;
   
    myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
   
    myField.selectionStart = startPos + myValue.length;
    myField.selectionEnd = startPos + myValue.length;
   
    if (restoreTop>0)
        {
        myField.scrollTop = restoreTop;
        }
    }
else
    {
    myField.value += myValue;
    }
}

function interceptTabs(evt, control)
{
key = evt.keyCode ? evt.keyCode : evt.which ? evt.which : evt.charCode;
if (key==9)
    {
    insertAtCursor(control, '\t');
    return false;
    }
else
    {
    return key;
    }
}

