//	Vamos a presuponer que el usuario es una persona inteligente...
var isIE = false;

//	Creamos una variable para el objeto XMLHttpRequest
var req;

function SetContainerHTML(id,html,processScripts) {
	mydiv = document.getElementById(id);
	mydiv.innerHTML = html;
	
	if(processScripts!=false){
		var elementos = mydiv.getElementsByTagName('script');
		
		for(i=0;i<elementos.length;i++) {
			var elemento = elementos[i];
			nuevoScript = document.createElement('script');
			nuevoScript.text = elemento.innerHTML;
			nuevoScript.type = 'text/javascript';

			if(elemento.src!=null && elemento.src.length>0)
			nuevoScript.src = elemento.src;
			elemento.parentNode.replaceChild(nuevoScript,elemento);
		}
	}
}


var Utf8 = {
    //Convierte de UTF-8 a ISO
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

//	Creamos una funcion para cargar los datos en nuestro objeto.
//	Logicamente, antes tenemos que crear el objeto.
//	Vease que la sintaxis varia dependiendo de si usamos un navegador decente
//	o Internet Explorer
function cargaXML(url) {
	//	Primero vamos a ver si la URL es una URL :)
	if(url==''){
		return;
	}
	//	Usuario inteligente...
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		//evalScripts:true,
		req.open("POST", url, { method: "post", evalScripts:true });
		req.send(null);
	//	...y usuario de Internet Explorer Windows
	} else if (window.ActiveXObject) {
		isIE = true;
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processReqChange;
			req.open("GET", url, true);
			req.send();
		}
	}

	var resultado = document.getElementById("resultado");
	resultado.innerHTML = "";
	
}

//	Funcion que se llama cada vez que se dispara el evento onreadystatechange
//	del objeto XMLHttpRequest
function processReqChange(){
	var detalles = document.getElementById("detalles");
	var scs=req.responseText.extractScript(); //capturamos los scripts 
	if(req.readyState == 4){
		detalles.innerHTML = req.responseText.stripScript();//eliminamos los scripts... ya son innecesarios  
		scs.evalScript(); 
		//detalles.innerHTML = "en construccion";
		//SetContainerHTML(detalles, req.responseText, true);		
	} else {
		detalles.innerHTML = '<div style="background-color:#FFFFFF; width:100%;"><img src="/images/Cargando.gif" /></div>';
	}
}

function cargaXML2(url, detalle) {
	var selec_tribu=document.getElementById('select_tribunal');
	var selec_sala=document.getElementById('select_sala');
	var selec_provincia=document.getElementById('select_provincia');
	var selec_jurisdiccion=document.getElementById('select_jurisdiccion');
	var selec_fuero=document.getElementById('select_fuero');
	var id_tribu='?select_tribunal='+document.getElementById('select_tribunal').options[document.getElementById('select_tribunal').selectedIndex].value;
	var id_sala='&select_sala='+selec_sala.options[selec_sala.selectedIndex].value;
	var id_provincia='&select_provincia='+selec_provincia.options[selec_provincia.selectedIndex].value;
	var id_jurisdiccion='&select_jurisdiccion='+selec_jurisdiccion.options[selec_jurisdiccion.selectedIndex].value;
	var id_fuero='&select_fuero='+selec_fuero.options[selec_fuero.selectedIndex].value;
	//	Primero vamos a ver si la URL es una URL :)
	if(url==''){
		return;
	}
	//	Usuario inteligente...
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange2;
		req.open("POST", url+id_tribu+id_sala+id_provincia+id_jurisdiccion+id_fuero, { method: "post", evalScripts:true });
		req.send(null);
	//	...y usuario de Internet Explorer Windows
	} else if (window.ActiveXObject) {
		isIE = true;
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processReqChange2;
			req.open("GET", url+id_tribu, true);
			req.send();
		}
	}

	//var resultado = document.getElementById("resultado");
	//resultado.innerHTML = "";
	
}

//	Funcion que se llama cada vez que se dispara el evento onreadystatechange
//	del objeto XMLHttpRequest
function processReqChange2(detalle){
	var detalles = document.getElementById('combos_juris');
	//alert(req.responseText);
	if(req.readyState == 4){
		detalles.innerHTML = req.responseText;
	} else {
		detalles.innerHTML = '<div style="background-color:#FFFFFF; width:100%;"><img src="/images/Cargando.gif" /></div>';
	}
}



function tabSeleccionado(id){
	var tabla=document.getElementById('solapetas').rows[0].cells;
	var i=0;
	document.getElementById(id).className='solapa activeTab';
	document.getElementById('solValor').value=id;
	for(i=0; i<tabla.length; i++){
		if(tabla[i].id!='espacio' && tabla[i].id!=id){
			tabla[i].className='solapa';
		}
	}
}

/* Devuelve el valor del Hidden */
function solapaActiva(){
	return document.getElementById('solValor').value;
}

function valorHiddenOut(id){
	if(document.getElementById('solValor').value==id){
		document.getElementById(id).className='solapa activeTab';
	}else{
		document.getElementById(id).className='solapa';	
	}
}

function valorHiddenOver(id){
	if(document.getElementById('solValor').value==id){
		document.getElementById(id).className='solapa activeTab';
	}else{
		document.getElementById(id).className='solapaOver';	
	}
}


function chequear_submit_doctrina() {
	if (document.bbd.enviar.value == 0) {
		return false;
	}
	
}

function buscar_jurisprudencia_basica() {
	
	/* RECORRER PARA VERIFICAR SI CHEQUEO ALGUN PRODUCTO */
	var cont = 0;
	var aPrd = new Array();
	
	//document.bbj['aProductos[]'].push("ok");
	
	for (var i=0;i < document.listaProductos['add_productos[]'].length;i++) {
		var elemento = document.listaProductos['add_productos[]'][i];
	

		if ( elemento.checked ){
			aPrd.push( elemento.value );
			cont++;
		}
	}	
				
	if (cont == 0){
		alert("Debe asignar un producto al usuario");
		return false;
	}
	
	if(document.getElementById('palabras').value.length<5){
		alert("Debe escribir al menos 5 caracteres");
		return false;
	}
	
	document.bbj.aProductos.value = aPrd;
	
	document.bbJ.action = "index.php?";
	/* document.bbd.action = "?resultado=201"; */
	document.bbj.submit();
	return true;
}

function retorno_productos_elegidos() {
	var cont = 0;
	var xPrd = "";
	var concat = "";
	
	for (var i=0;i < document.listaProductos['add_productos[]'].length;i++) {
		var elemento = document.listaProductos['add_productos[]'][i];
	

		if ( elemento.checked ){
			xPrd = xPrd + concat + elemento.value;
			concat = ", ";
			cont++;
		}
	}

	return xPrd;
}


function buscar_jurisprudencia_avanzada(nro_pagina) {
	
	/* RECORRER PARA VERIFICAR SI CHEQUEO ALGUN PRODUCTO */
	var cont = 0;
	var aPrd = new Array();
	var xPrd = "";
	var concat = "";
	
	//alert("nro caract. "+document.baj.inputString.value);
	if (document.baj.inputString.value != "") {
		alert("Hay una voz elegida, pero NO seleccionada. De un click en el signo + si quiere agregar esta voz al filtro de busqueda, o limpie el campo");
		return false;
	}
	
	//document.bbj['aProductos[]'].push("ok");
	
	for (var i=0;i < document.listaProductos['add_productos[]'].length;i++) {
		var elemento = document.listaProductos['add_productos[]'][i];
	

		if ( elemento.checked ){
			//aPrd.push( elemento.value );
			
			xPrd = xPrd + concat + elemento.value;
			concat = ", ";
			cont++;
		}
	}	
				
	if (cont == 0){
		alert("Debe asignar un producto al usuario");
		return false;
	}
	
	// document.bad.aProductos.value = aPrd;
	document.baj.aProductos.value = xPrd;
	document.baj.pag.value = nro_pagina;
	
	//document.bad.action = "index.php?";
	
	/*------- Verifica que la diferencia de fechas no sea mayor a 2--------*/
	if (document.getElementById('input_fecha_desde') != null && document.getElementById('input_fecha_desde').value != "") {
		var fecha_desde = document.getElementById('input_fecha_desde').value;
		var fecha_hasta = document.getElementById('input_fecha_hasta').value;
		var fecha_actual = document.getElementById('input_fecha_actual').value;
		if(fecha_hasta=="" && fecha_desde!=""){
			document.getElementById('input_fecha_hasta').value=document.getElementById('input_fecha_actual').value;
			fecha_hasta=fecha_actual;
		}
		dias=restaFechas(fecha_desde, fecha_hasta);
		if(dias>730){
			alert("La diferencia de fechas no puede ser mayor a dos aņos");
			return false;
		}
	}
	
	/*-------------------------------- FIN --------------------------------*/
	
	document.baj.submit();
	return true;
}



function restaFechas(fecha1, fecha2){
	//Obtiene los datos del formulario   
	CadenaFecha1 = fecha1;
	CadenaFecha2 = fecha2;
	      
	//Obtiene dia, mes y aņo   
	var fecha1 = new fecha( CadenaFecha1 );     
	var fecha2 = new fecha( CadenaFecha2 );  
	      
	//Obtiene objetos Date   
	var miFecha1 = new Date( fecha1.anio, fecha1.mes, fecha1.dia ); 
	var miFecha2 = new Date( fecha2.anio, fecha2.mes, fecha2.dia );  
	  
	//Resta fechas y redondea   
	var diferencia = miFecha2.getTime() - miFecha1.getTime();
	var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24));   
	var segundos = Math.floor(diferencia / 1000);
	//alert ('La diferencia es de ' + dias + ' dias,\no ' + segundos + ' segundos.');
	return dias;
}

function fecha( cadena ) {   
	  
   //Separador para la introduccion de las fechas   
   var separador = "/";
  
   //Separa por dia, mes y aņo   
   if ( cadena.indexOf( separador ) != -1 ) {   
        var posi1 = 0;
        var posi2 = cadena.indexOf( separador, posi1 + 1 );
        var posi3 = cadena.indexOf( separador, posi2 + 1 );  
        this.dia = cadena.substring( posi1, posi2 );
        this.mes = cadena.substring( posi2 + 1, posi3 );   
        this.anio = cadena.substring( posi3 + 1, cadena.length );   
   } else {   
        this.dia = 0;
        this.mes = 0;  
        this.anio = 0;      
   }   
	}   
///////////////////// Ver que onda con esta funcion
/*
function verificar_fecha_superiorActual(pfechaIngresada){
	var dia=new Date(); 
	var fecha = dia.getYear()+"-"+(dia.getMonth()+1)+"-"+ dia.getDate(); 
	var datePat = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; 
	
	var fecha0 = fecha; 
	var matchArray0 = fecha0.match(datePat); 
	month0 = matchArray0[3]; 
	day0 = matchArray0[5]; 
	year0 = matchArray0[1]; 


	var fecha1 = pfechaIngresada; 
	var matchArray1 = fecha1.match(datePat); 
	month1 = matchArray1[3]; 
	day1 = matchArray1[5]; 
	year1 = matchArray1[1]; 


	if(parseInt(year1)==parseInt(year0)){ 
		if(parseInt(month1)>parseInt(month0)){ 
			return true; 
		}else if(parseInt(year1)==parseInt(year0) && parseInt(month1)==parseInt(month0) && parseInt(day1)>=parseInt(day0)){ 
				return true; 
			}else{ 
				return false; 
			} 
		}else if(parseInt(year1)>parseInt(year0)){ 
		return true; 
	} 
}*/


function buscar_doctrina_basica() {
	
	/* RECORRER PARA VERIFICAR SI CHEQUEO ALGUN PRODUCTO */
	var cont = 0;
	var aPrd = new Array();
	
	//document.bbj['aProductos[]'].push("ok");
	
	for (var i=0;i < document.listaProductos['add_productos[]'].length;i++) {
		var elemento = document.listaProductos['add_productos[]'][i];
	

		if ( elemento.checked ){
			aPrd.push( elemento.value );
			cont++;
		}
	}	
				
	if (cont == 0){
		alert("Debe asignar un producto al usuario");
		return false;
	}
	
	if(document.getElementById('palabras').value.length<5){
		alert("Debe escribir al menos 5 caracteres");
		return false;
	}
		
	
	document.bbd.aProductos.value = aPrd;
	document.bbd.action = "index.php?id_rec=00#busqueda";
	//document.bbd.submit();
	return true;
}


function buscar_doctrina_avanzada(nro_pagina) {
	
	/* RECORRER PARA VERIFICAR SI CHEQUEO ALGUN PRODUCTO */
	var cont = 0;
	var aPrd = new Array();
	var xPrd = "";
	var concat = "";
	
	//document.bbj['aProductos[]'].push("ok");
	
	if (document.bad.inputString.value != "") {
		alert("Hay una voz elegida, pero NO seleccionada. De un click en el signo + si quiere agregar esta voz al filtro de busqueda, o limpie el campo");
		return false;
	}
	
	if (document.bad.inputAutor.value != "") {
		alert("Hay un autor elegido, pero NO seleccionado. De un click en el signo + si quiere agregar este autor al filtro de busqueda, o limpie el campo");
		return false;
	}
	
	for (var i=0;i < document.listaProductos['add_productos[]'].length;i++) {
		var elemento = document.listaProductos['add_productos[]'][i];
	

		if ( elemento.checked ){
			//aPrd.push( elemento.value );
			
			xPrd = xPrd + concat + elemento.value;
			concat = ", ";
			cont++;
		}
	}	
				
	if (cont == 0){
		alert("Debe asignar un producto al usuario");
		return false;
	}
	
	// document.bad.aProductos.value = aPrd;
	document.bad.aProductos.value = xPrd;
	document.bad.pag.value = nro_pagina;
	
	//document.bad.action = "index.php?";
	document.bad.submit();
	return true;
}


function buscar_doctrina_avanzada_familia(nro_pagina) {
	
	if (document.bad.inputString.value != "") {
		alert("Hay una voz elegida, pero NO seleccionada. De un click en el signo + si quiere agregar esta voz al filtro de busqueda, o limpie el campo");
		return false;
	}
	
	if (document.bad.inputAutor.value != "") {
		alert("Hay un autor elegido, pero NO seleccionado. De un click en el signo + si quiere agregar este autor al filtro de busqueda, o limpie el campo");
		return false;
	}
		
	document.bad.pag.value = nro_pagina;
	document.bad.submit();
	return true;
}

//********** FUNCIONES DE AUTOCOMPLETAR *********//
function lookup(inputString, letra) {
	var productos = retorno_productos_elegidos();
	//return false;
	
	if(inputString.length == 0) {
		// Hide the suggestion box.
		$('#suggestions').hide();
	} else {
		$.post("includes/autoCompletar/rpc.php?xPrd="+productos+"&letra="+letra, {queryString: ""+inputString+""}, function(data){
			if(data.length >0) {
				$('#suggestions').show();
				$('#autoSuggestionsList').html(data);
			}
		});
	}
} // lookup

function fill(thisValue, id) {
	$('#inputString').val(thisValue);
	$('#inputStringId').val(id);
	/*$('#x_voz_id').val(id);*/
	setTimeout("$('#suggestions').hide();", 350);
}

function lookup2(inputString) {
	if(inputString.length == 0) {
		// Hide the suggestion box.
		$('#suggestionsAutor').hide();
	} else {
		$.post("includes/autoCompletar/autores.php", {queryString: ""+inputString+""}, function(data){
			if(data.length >0) {
				$('#suggestionsAutor').show();
				$('#autoSuggestionsListAutor').html(data);
			}
		});
	}
} // lookup

function fill2(thisValue, id) {
	$('#inputAutor').val(thisValue);
	$('#inputAutorId').val(id);
	/*$('#x_voz_id').val(id);*/
	setTimeout("$('#suggestionsAutor').hide();", 350);
}

function lookupfamilia(inputString, letra) {
	//var productos = retorno_productos_elegidos();
	//return false;
	
	if(inputString.length == 0) {
		// Hide the suggestion box.
		$('#suggestions').hide();
	} else {
		$.post("includes/autoCompletar/voces.php?letra="+letra, {queryString: ""+inputString+""}, function(data){
			if(data.length >0) {
				$('#suggestions').show();
				$('#autoSuggestionsList').html(data);
			}
		});
	}
} // lookup

//************ FIN FUNCIONES DE AUTOCOMPLETAR *************//

function agregar_varios(nombre_combo, nombre_input){
	var combo=document.getElementById(nombre_combo);
	var comboId=document.getElementById(nombre_combo+'Id');
	var input=document.getElementById(nombre_input);
	var inputId=document.getElementById(nombre_input+'Id');
	var vecInputId;
	var repetido=false;
	
	if((combo.value).length!=0){
		vecInputId=inputId.value.split(", ");
		for(var i in vecInputId){
			if(vecInputId[i]==comboId.value){
				repetido=true;
			}
		}
		if(repetido==false){
			input.value+=combo.value+' - ';
			inputId.value+=comboId.value+', ';
			combo.value="";
		}else{
			alert("Ya se encuentra ingresada la opcion");
			combo.value="";
		}
	}else{
		alert("Debe Seleccionar una opcion");
	}
}

function quitar_varios(nombre_combo, nombre_input){
	var combo=document.getElementById(nombre_combo);
	var comboId=document.getElementById(nombre_combo+'Id');
	var input=document.getElementById(nombre_input);
	var inputId=document.getElementById(nombre_input+'Id');
	var vecInputId=inputId.value.split(", ");
	var vecInput=input.value.split(" - ");
	var i=0;
	if((inputId.value).lenght!=0){
		for(i in vecInputId){
		}
		inputId.value="";
		input.value="";
		for(var a=0; a<i-1; a++){
			inputId.value+=vecInputId[a]+', ';
			input.value+=vecInput[a]+' - ';
		}
	}
}

/*************************************************************************/
/********* FAMILIA *************/
function buscar_jurisprudencia_avanzada_familia(nro_pagina) {
	
	/* RECORRER PARA VERIFICAR SI CHEQUEO ALGUN PRODUCTO */
	var cont = 0;
	
	//alert("nro caract. "+document.baj.inputString.value);
	if (document.baj.inputString.value != "") {
		alert("Hay una voz elegida, pero NO seleccionada. De un click en el signo + si quiere agregar esta voz al filtro de busqueda, o limpie el campo");
		return false;
	}
	
	document.baj.pag.value = nro_pagina;
	
	/*------- Verifica que la diferencia de fechas no sea mayor a 2--------*/
	/*if (document.getElementById('input_fecha_desde').value != Null ) {
		var fecha_desde = document.getElementById('input_fecha_desde').value;
		var fecha_hasta = document.getElementById('input_fecha_hasta').value;
		var fecha_actual = document.getElementById('input_fecha_actual').value;
		if(fecha_hasta=="" && fecha_desde!=""){
			document.getElementById('input_fecha_hasta').value=document.getElementById('input_fecha_actual').value;
			fecha_hasta=fecha_actual;
		}
		dias=restaFechas(fecha_desde, fecha_hasta);
		if(dias>730){
			alert("La diferencia de fechas no puede ser mayor a dos aņos");
			return false;
		}
	}
	*/
	/*-------------------------------- FIN --------------------------------*/
	
	document.baj.submit();
	return true;
}
function limpiarInput(input){
	document.getElementById(input).value="";
}

