var READY_STATE_COMPLETE=4

var peticion_http = null

var valoruni = 0

function inicializa_xhr() {

	if(window.XMLHttpRequest)

		{return new XMLHttpRequest()

	}else if(window.ActiveXObject)

		{return new ActiveXObject("Microsoft.XMLHTTP")

	}

}

function s_mostrar(){
	msol = document.getElementById("solicitud")
	if(msol.length == 0){return 0;}

	cual = msol.options[msol.selectedIndex].text

	msol.disabled = true

	document.varios.encontrada.value = 	cual

	buscar()

}

function s_saltar(){

	var sol = document.getElementById("codigo")

	var largo = sol.value

	if(largo.length == 6){

		//verifica repetidos *************************************

		var sol2 = document.getElementById("solicitud")

		for (i=0;i<=sol2.length-1;i++) {

			//alert(sol2.options[i].text + " - " + sol)

			if(sol2.options[i].text == largo){alert("El n\u00famero de solicitud ya existe en la lista");sol.value = "";return 0;}

		}

		bot = document.getElementById("xx")

		bot.disabled = false

		bot.focus()

	}

}

function s_eliminar(){

	sel = document.getElementById("solicitud")

	indice = sel.selectedIndex

	selv = sel.options[indice].value

	valoruni = document.form2.valor.value

	valoruni = valoruni - selv

	document.form2.valor.value = valoruni

	sel.options[indice] = null

	document.getElementById("totalsol").innerHTML = "Cant. de Publicaciones: " + sel.length + "<br>Valor Total: <b>" + formatNumber(valoruni.toString()) + "</b>"

	document.getElementById("ventana").innerHTML = ""

	btel = document.getElementById("elimina")

	document.getElementById("detalles").style.display = "none"		

	if(sel.length == 0){btel.disabled = true}else{btel.disabled = false}

		if (sel.length == 0){

			document.getElementById("ppgg").style.display = "none"

		}

	

}

function s_numeros(evt){

	var nav4 = window.Event ? true : false;

	var key = nav4 ? evt.which : evt.keyCode;

	if (key == 13){buscar()}

	return (key == 8 || (key >= 48 && key <= 57));

}

//**********************FIN FUNCIONES DE LOTE*****************************************



function buscar(){

	soli = document.getElementById("codigo")

	codigo = soli.value

	//codigo = document.form1.codigo.value

	if(codigo == ""){

		if(document.getElementById("solicitud").text != ""){

			codigo = document.varios.encontrada.value

			//codigo = document.getElementById("solicitud").text

		}else{

			return 0

		}

	}

	var capa = document.getElementById("ventana")

	document.getElementById("instruccionInicial").style.display = "none"

	capa.style.display = "block"

	document.getElementById("detalles").style.display = "block"

	capa.innerHTML = '<img border="0" src="img/buscando.gif" width="100" height="26">'

	peticion_http = inicializa_xhr()

	if(peticion_http){

		peticion_http.onreadystatechange = verificar555

		peticion_http.open("POST", "buscar.php", true)

		peticion_http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

		var buscar = "codigo="+codigo+"&nocache=" + Math.random()

		peticion_http.send(buscar)

	}

}

function verificar555(){

	if(peticion_http.readyState == READY_STATE_COMPLETE){

		if(peticion_http.status == 200){

		msol = document.getElementById("solicitud")

		msol.disabled = false

		

			var capa = document.getElementById("ventana")

			capa.innerHTML = ""

			var r = peticion_http.responseText

			//alert(r)

			ops = r.split("##")

			//alert(ops);

			

			if(ops[0] == "pa"){

				//capa.innerHTML = "La Solicitud ya fue Pagada."

				alert("La Solicitud ya fue Pagada.");

				document.form1.codigo.value = ""

				return 0

			}

			

			if(ops[0] == "fueraplazo"){

				//capa.innerHTML = "La solicitud que Intenta Publicar <br />Se encuentra fuera del plazo establecido."

				alert("La solicitud que Intenta Publicar \nSe encuentra fuera del plazo establecido.");

				document.form1.codigo.value = ""				

				return 0

			}

			

			if(ops[0] == "ok"){

				/*var capa = document.getElementById("verPDF2");

				if(capa.style.display == "block"){

					capa.style.display = "none"

				}*/

				var imagen = ops[1];

				var texto = ops[2];

				var valor = ops[3];

				var fecha = ops[4];

				var aceptado = ops[5];

				var ultimo = ops[6];

				var idmail = ops[7];

				var totaljava = ops[8];

				/*var capa2 = document.getElementById("pago");

				capa2.style.display = "block";*/

				//document.getElementById("table100").style.display = "none";

				//document.form2.valor.value = "$" + valor;

				document.form2.fecha.value = fecha;

				document.form2.idParaMail.value = idmail;

			    document.getElementById("valorDiv").innerHTML = "$" + valor;

			    document.getElementById("fechaDiv").innerHTML = fecha;

				//document.getElementById("imagen").innerHTML = imagen;

			    //document.getElementById("texto").innerHTML = texto;

			    capa.innerHTML = imagen + texto;

				document.getElementById("aceptada").innerHTML = aceptado;

				document.getElementById("ultimo").innerHTML = ultimo;

				//document.varios.encontrada.value = "s"

				//alert(document.varios.encontrada.value)				

				

	//buscar(sol)	

	//if(document.getElementById("valorDiv").textContent == ""){alert("nooooo"); return 0;}

	//if(esta == "x"){alert("no encontrada"); return 0;}



	//if(sol.length < 6){alert("El Nº de solicitud debe tener mín. 6 caracteres"); return 0;}

	if(document.varios.encontrada.value == ""){

		valoruni = parseFloat(document.form2.valor.value);

		if(totaljava == ""){return 0;}

		soli = document.getElementById("codigo")

		sol = soli.value

		valoruni = valoruni + parseFloat(totaljava)		

		datos = document.getElementById("solicitud")

		var total = datos.options.length;

		document.form1.solicitud.length = total+1;

		if(total < 10){datos.size = total+1}

		btel = document.getElementById("elimina")

		if(datos.length == 0){btel.disabled = true}else{btel.disabled = false}

	    datos.options[total].value=totaljava

	    datos.options[total].text=sol

		soli.value = ""

		datos.options[total].selected = true

		soli.focus()

		bot = document.getElementById("xx")

		//bot.disabled = true

		largo = datos.length

		document.form2.valor.value = valoruni

		forvalor = formatNumber(valoruni.toString())

		document.getElementById("totalsol").innerHTML = "Cant. de Publicaciones: " + largo + "<br>Valor Total: <b>" + forvalor + "</b>"

		var ppp = document.getElementById("ppgg")

		if (ppp.style.display == "none"){

			ppp.style.display = "block"

		}

		totaljava = ""

		if(document.getElementById("totalsol").style.display == "none"){

			document.getElementById("totalsol").style.display = "block"

			document.getElementById("sporlote").style.display = "none";					

		}



	}

	document.varios.encontrada.value = ""				

			}

			if(ops[0] != "ok"){

				//alert(r)

				document.getElementById("detalles").style.display = "none"

				if(ops[0] != ""){

					//capa.innerHTML = "<font color=\"#FF0000\">ERROR<br>El n&uacute;mero de la solicitud  no se encuentra disponible o es incorrecto. Verif&iacute;quelo</font>"

					alert("El n\u00famero de la solicitud  no se encuentra disponible o es incorrecto.\nVerif\u00edquelo");

				document.form1.codigo.value = ""					

				}

				else

				{

					//capa.innerHTML = "El sistema no se encuentra disponible intentelo mas tarde."

					alert("El sistema no se encuentra disponible, int\u00e9ntelo m\u00e1s tarde.");

					}

				return 0

			}

			

		}

	}

}



function enviarpago(){

	if(document.form2.valor.value == 0){alert("No hay solicitudes para publicar");return 0;}

	if(!document.form1.verifica.checked){

		alert("Confirme que solicita publicar esta Solicitud \nPinche en: Acepto publicar este documento.");

		return 0;

	}

	document.form3.fechapub1.value = document.form2.fecha.value

	document.form3.valor1.value = formatNumber(document.form2.valor.value)

	

	document.getElementById("table103").style.display = "block";	

	//document.getElementById("pagar1").style.display = "none";	

	//document.getElementById("pago").innerHTML = "";	

	document.getElementById("table100").style.display = "none";
	document.getElementById("verPDF2").style.display = "none";


	var sol = document.getElementById("solicitud")

	var textosol = ""

	var valorsol = ""

	document.form3.totalsolicitudes2.value = sol.length

	for (i=0;i<=sol.length-1;i++) {

		 textosol = textosol + sol.options[i].text + ", "

		 valorsol = valorsol + sol.options[i].value + ", "

	}

	document.form3.lassolicitudes.value = textosol;		

	textosol = textosol.substring(0, textosol.length-2)

	document.form3.numerosolicitudes.value = textosol

	document.form3.valorsolicitudes.value = valorsol	

	document.getElementById("muestrasolicitudes").innerHTML = textosol

}



function limpiar(){

	document.form3.rut.value = "";

	document.form3.nomrz.value = "";

	document.form3.paterno.value = "";	

	document.form3.materno.value = "";	

	document.form3.direccion.value = "";	

	document.form3.comuna.value = "";	

}



function enviar(){

	if (document.form3.pagador.value == "0"){

		if(document.form3.rut.value == ""){

			alert("DEBE INGRESAR EL RUT DEL PAGADOR")

			return 0

		}

		if(document.form3.rut.value == ""){

			alert("DEBE INGRESAR EL RUT DEL PAGADOR")

			return 0

		}

		var r = document.form3.rut.value;

		r = r.replace(/\./g, ""); 

		r = r.substring(0,r.length-2);

		if(parseInt(r)<50000000){

			if(document.form3.nomrz.value == ""){

				alert("DEBE INDICAR EL NOMBRE DEL PAGADOR")

				return 0

			}

			if(document.form3.paterno.value == ""){

				alert("DEBE INDICAR EL APELLIDO PATERNO DEL PAGADOR")

				return 0

			}

			if(document.form3.materno.value == ""){

				alert("DEBE INDICAR EL APELLIDO MATERNO DEL PAGADOR")

				return 0

			}

		}else{

			if(document.form3.nomrz.value == ""){

				alert("DEBE INDICAR LA RAZON SOCIAL DEL PAGADOR")

				return 0

			}

		}

		//CORREO

		var s = document.form3.email.value;

		var filter=/^[A-Za-z][A-Za-z0-9_.\-]*@[A-Za-z0-9-_.]+\.[A-Za-z0-9_.]+[A-za-z]$/;

		if (s.length == 0 ){

			alert("DEBE INDICAR UNA DIRECCION DE CORREO ELECTRONICO")

			return 0

		}

		if (filter.test(s)){

			//

		}else{

			alert("CORREO ELECTRONICO NO VALIDO");

			return 0

		}

	}

		if(document.form3.direccion.value == ""){

			alert("DEBE INGRESAR LA DIRECCION DEL PAGADOR")

			return 0

		}

		if(document.form3.comuna.value == "0"){

			alert("DEBE INGRESAR LA COMUNA DE RESIDENCIA DEL PAGADOR")

			return 0

		}

	document.form3.texcomuna.value = document.form3.comuna.options[document.form3.comuna.selectedIndex].text

	document.form3.submit();	

}

function verejemplo(){

	var capa = document.getElementById("verPDF2");

	if(capa.style.display == "block"){

		//capa.style.display = "none"

	}else{

		capa.style.display = "block"	

	}

	obj = document.getElementById("iframe");

	obj.src="img/ejemplo.png";

	obj.height="570";

}

function fpago(){

	var capa = document.getElementById("verPDF2");

	if(capa.style.display == "block"){

		capa.style.display = "none"

	}else{

		capa.style.display = "block"	

	}

	obj = document.getElementById("iframe");

	obj.src="img/fpago.htm";

	obj.height="570";

}



function validarut(){

	if(document.form3.pagador.value == "0"){

		if(document.form3.rut.value != ""){

			Rut(document.form3.rut.value)		

		}

		var r = document.form3.rut.value;

		r = r.replace(/\./g, ""); 

		r = r.substring(0,r.length-2);

		if(parseInt(r)<50000000){

			document.getElementById('paterno').readOnly=false

			document.getElementById('materno').readOnly=false					

		}else{

		document.getElementById('paterno').readOnly=true

		document.getElementById('materno').readOnly=true	

		document.getElementById('paterno').value=""

		document.getElementById('materno').value=""						

		}

	}

} 

function volver(){

	document.getElementById("table103").style.display = "none"

	document.getElementById("table100").style.display = "block"	

	document.getElementById("verifica").checked = false

}

function formatNumber(num){

prefix = "$";

var splitStr = num.split('.');

var splitLeft = splitStr[0];

var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';

var regx = /(\d+)(\d{3})/;

while (regx.test(splitLeft)) {

splitLeft = splitLeft.replace(regx, '$1' + '.' + '$2');

}

return prefix + splitLeft + splitRight;

}

function muestralote(){
		datos = document.getElementById("solicitud")

		if(datos.length > 0){
			var re = confirm("Si elige esta opcci\u00f3n, los datos ya ingresados se perder\u00e1n. Desea continuar?")
			if(re){
				//ok
				datos.size = 0;
				datos.length = 0;
			}else{
				return 0;	
			}
		}
		
	
		document.form1.reset();
		document.form3.reset();
		document.form2.reset();
		document.getElementById("elimina").disabled = true

	document.getElementById("totalsol").style.display = "none";

	document.getElementById("detalles").style.display = "none";
	
	document.getElementById("ppgg").style.display = "none";

	document.getElementById("sporlote").style.display = "block";	

	document.getElementById("unico").style.display = "none";

	document.getElementById("ventana").style.display = "none";

	document.getElementById("ventana").innerHTML = "";

	document.getElementById("instruccionInicial").style.display = "none";

	document.getElementById("instruccionLotes").style.display = "block";
	
	document.getElementById("totalsol").innerHTML = "Cant. de Publicaciones: 0<br>Valor Total: 0</b>";	

}

function cancelalote(){

	document.getElementById("totalsol").style.display = "block";

	document.getElementById("sporlote").style.display = "none";	

	document.getElementById("lote").value = "";

	document.getElementById("unico").style.display = "block";	

	document.getElementById("instruccionInicial").style.display = "block";

	document.getElementById("instruccionLotes").style.display = "none";

}

function buscarlote(){

	lote = document.getElementById("lote")

	codigos = lote.value

	if(codigos == ""){alert("Debe indicar los n\u00fameros de solicitud");return 0;}

	var capa = document.getElementById("ventana")

	ventana.style.display = "block"

	capa.innerHTML = '<font color="#FF0000"><b>Procesando ...</b></font>';

	peticion_http = inicializa_xhr()

	if(peticion_http){

		peticion_http.onreadystatechange = resultado

		peticion_http.open("POST", "procesalotes.php", true)

		peticion_http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

		var buscar = "codigos="+codigos+"&nocache=" + Math.random()

		peticion_http.send(buscar)

	}

}

function resultado(){

	if(peticion_http.readyState == READY_STATE_COMPLETE){

		if(peticion_http.status == 200){

			var r = peticion_http.responseText

			r = r.split("##");

			var tot = r[0];

			var valor = r[1];

			var valores = r[2].split(",");

			var soli = r[3].split(",");

			var fallo = r[4];

			var vjava = r[5];	

			var fechapub = r[6];

			document.form2.fecha.value = fechapub;

			if(tot > 0){

				fallo = "<strong>Se han cargado exitosamente "+tot +" solicitudes.</strong></br> - Haga clic sobre el n&uacute;mero de cada solicitud en la lista del costado izquierdo de su pantalla.</br> - Revise el texto, e imagen si corresponde.</br></br><strong>En caso de existir cualquier error:</strong></br> - Haga clic sobre el  n&uacute;mero de solicitud y luego en el bot\u00f3n \"Quitar Seleccionada\".</br></br> " + fallo;

			}

			datos = document.getElementById("solicitud");

			//limpiar datos \u00fanicos

			document.form1.codigo.value = "";

			document.form1.solicitud.length = 0;

			//**************

			for (i=0;i<=tot-1;i++) {

				var total = datos.options.length;

				document.form1.solicitud.length = total+1;

				if(total < 10){datos.size = total+1}

			

			    datos.options[total].value=valores[i];

			    datos.options[total].text=soli[i];

			}

		

			document.form2.valor.value = vjava;

			document.getElementById("sporlote").style.display = "none";

			document.getElementById("instruccionInicial").style.display = "none";

			document.getElementById("ventana").style.display = "block";

			document.getElementById("ventana").innerHTML = fallo;

			document.getElementById("totalsol").style.display = "block";

			document.getElementById("ppgg").style.display = "block";			

			document.getElementById("detalles").style.display = "none";					

			document.getElementById("botontexto").style.display = "block";			

			document.getElementById("totalsol").innerHTML = "Cant. de Publicaciones: " + tot + "<br>Valor Total: <b>" + valor + "</b>";

			document.getElementById("elimina").disabled = false;

			document.getElementById("unico").style.display = "block";
			
			document.getElementById("instruccionLotes").style.display = "none";

			document.form1.lote.value = "";		

		}

	}

}
function generaPDF(){
		var todas="";
				obj = document.getElementById("iframe");
				obj.src="blank.htm";	
				
		var sol2 = document.getElementById("solicitud")
		for (i=0;i<=sol2.length-1;i++) {
			todas = todas + sol2.options[i].text + ",";
			//alert(i + " - " + sol2.options[i].text);
			//return 0;
		}	
		fxx = document.form2.fecha.value;

	peticion_http = inicializa_xhr()
	if(peticion_http){
		peticion_http.onreadystatechange = muestraPDF
		peticion_http.open("POST", "generaPDF.php", true)
		peticion_http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
		var buscar = "todas="+todas+"&fxx="+fxx+"&nocache=" + Math.random()
		peticion_http.send(buscar)
	}	
}
function muestraPDF(){
	if(peticion_http.readyState == READY_STATE_COMPLETE){
		if(peticion_http.status == 200){
			var r = peticion_http.responseText
			if(r != ""){
				window.open("PDFs/"+r+".pdf","verPDF","width=600,height=500,menubar=no,Scrollbars=YES")
			}
		}
	}
}
