dojo.require("dojo.parser");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.ComboBox");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.dijit");
dojo.require("dijit.Dialog");
var listaOrden = [];

function cargarDatos() {
	var strFecha = formarFecha();
	dojo.byId("date1").value = strFecha;
	dojo.byId("date2").value = strFecha;

	cargarCombo(1, "divEstatus", "cbEstatus", "estatus", ['emisor',
			'tipodocumento', 'tema', 'subtema'], ['*', '*', '*', '*']);
	cargarCombo(2, "divEmisor", "cbEmisor", "emisor", ["estatus",
			"tipodocumento", "tema", "subtema"], ['*', '*', '*', '*']);
	cargarCombo(3, "divTipoDoc", "cbTipodocumento", "tipodocumento", ['emisor',
			'estatus', 'tema', 'subtema'], ['*', '*', '*', '*']);
	cargarCombo(4, "divTema", "cbTema", "tema", ['emisor', 'estatus',
			'tipodocumento', 'subtema'], ['*', '*', '*', '*']);
	cargarCombo(5, "divSubTema", "cbSubtema", "subtema", ['emisor', 'estatus',
			'tipodocumento', 'tema'], ['*', '*', '*', '*']);
	crearCbOrdenar("divOrden", "cbOrden");
	var editBox = dojo.byId('consulta');
	editBox.focus();
}

function formarFecha() {
	var fecha = new Date();
	var mes = cacularMes(fecha.getMonth());
	var dia = calcularDia(fecha.getDate());
	var strFecha = "";
	if (dia == "") {
		strFecha = fecha.getFullYear() + '-' + mes + '-' + fecha.getDate();
	} else {
		strFecha = fecha.getFullYear() + '-' + mes + '-' + dia;
	}
	return strFecha;
}

function cacularMes(valor) {
	var mes;
	switch (valor) {
		case 0 :
			mes = "01";
			break;
		case 1 :
			mes = "02";
			break;
		case 2 :
			mes = "03";
			break;
		case 3 :
			mes = "04";
			break;
		case 4 :
			mes = "05";
			break;
		case 5 :
			mes = "06";
			break;
		case 6 :
			mes = "07";
			break;
		case 7 :
			mes = "08";
			break;
		case 8 :
			mes = "09";
			break;
		case 9 :
			mes = "10";
			break;
		case 10 :
			mes = "11";
			break;
		case 11 :
			mes = "12";
			break;
	}
	return mes;
}

function calcularDia(valor) {
	var dia = '';
	switch (valor) {
		case 1 :
			dia = "01";
			break;
		case 2 :
			dia = "02";
			break;
		case 3 :
			dia = "03";
			break;
		case 4 :
			dia = "04";
			break;
		case 5 :
			dia = "07";
			break;
		case 6 :
			dia = "06";
			break;
		case 7 :
			dia = "07";
			break;
		case 8 :
			dia = "08";
			break;
		case 9 :
			dia = "09";
			break;
	}
	return dia;
}

function cargarCombo(id, divCb, idCb, campo, arrayCampos, arrayValores) {

	var info = new datosCombo(campo, arrayCampos, arrayValores);
	dojo.xhrPost({
		url : '/normsearch/llenarCombo.htm',
		content : info,
		contentType : "application/x-www-form-urlencoded;charset=UTF-8",
		load : function(data, event) {
			document.getElementById('img' + id).style.display = 'block';
			var result = dojo.fromJson(data);
			var elementos = [];

			elementos.push({
				name : 'TODOS'
			});
			dojo.forEach(result.result, function(item) {
				elementos.push({
					name : item
				});
			});
			var options = new dojo.data.ItemFileWriteStore({
				data : {
					identifier : "name",
					items : elementos
				}
			});
			var myDijit = new dijit.form.ComboBox({
				id : idCb,
				value : 'TODOS',
				store : options,
				searchAttr : 'name',
				style : "width:300px;",// font-size:9px;",
				onChange : modificarCombo
			});
			dojo.byId(divCb).appendChild(myDijit.domNode);
			dojo.connect(dojo.byId(idCb), 'onchange', 'modificarCombo');
			document.getElementById('img' + id).style.display = 'none';
		},
		error : function(data, event) {
			// document.getElementById("divMensanjeError").innerHTML="&iexcl; No
			// se pudo conectar con el servidor &#33;";
		displayError(data, event);
	}
	});
}

function estadoFechas() {
	var date1 = dijit.byId('date1');
	var date2 = dijit.byId('date2');
	if (document.getElementById("cb").checked) {
		date1.attr('disabled', !date1.disabled);
		date2.attr('disabled', !date2.disabled);
	} else {
		date1.attr('disabled', !date1.disabled);
		date2.attr('disabled', !date2.disabled);
	}
}

function modificarCombo() {
	console.debug('******************** modificarCombo ********************')
	// var editBox = dojo.byId('consulta');
	// editBox.focus();
	var idActual = this.id;
	console.debug('id : ' + this.id);
	console.debug('value : ' + this.value);
	if (this.id == 'cbSubtema') {
		mostrarDialogo();
		ocultarDialogo();
		return;
	}
	var id;
	var objetivo = "";
	var campo = "";
	var lstParam = [];
	var lstValues = [];
	var estatus = obtenerValorEstatus();
	var emisor;
	var tipodocumento;
	var elemento;

	switch (this.id) {
		case 'cbEstatus' :
			console.debug('entro al case cbEstatus');
			campo = 'emisor';
			lstParam = ["estatus", "tipodocumento", "tema", "subtema"];
			lstValues = [estatus, '*', '*', '*'];
			objetivo = "cbEmisor";
			id = 2;
			elemento = 'Estatus';
			if (estatus == '*')
				agregarCbOrdenar(elemento);
			else
				eliminarCbOrdenar(elemento);
			break;
		case 'cbEmisor' :
			console.debug('entro al case cbEmisor');
			campo = 'tipodocumento';
			lstParam = ["estatus", "emisor", "tema", "subtema"];
			emisor = obtenerValorEmisor();
			lstValues = [estatus, emisor, '*', '*'];
			objetivo = "cbTipodocumento";
			id = 3;
			elemento = 'Emisor';
			if (emisor == '*')
				agregarCbOrdenar(elemento);
			else
				eliminarCbOrdenar(elemento);
			break;
		case 'cbTipodocumento' :
			console.debug('entro al case cbTipodocumento');
			campo = 'tema';
			lstParam = ["estatus", "emisor", "tipodocumento", "subtema"];
			emisor = obtenerValorEmisor();
			tipodocumento = obtenerValorTipodocumento();
			lstValues = [estatus, emisor, tipodocumento, '*'];
			objetivo = "cbTema";
			id = 4;
			elemento = 'Tipo de Documento';
			if (tipodocumento == '*')
				agregarCbOrdenar(elemento);
			else
				eliminarCbOrdenar(elemento);
			break;
		case 'cbTema' :
			console.debug('entro al case cbTema');
			campo = 'subtema';
			lstParam = ["estatus", "emisor", "tipodocumento", "tema"];
			emisor = obtenerValorEmisor();
			tipodocumento = obtenerValorTipodocumento();
			var tema = obtenerValorTema();
			lstValues = [estatus, emisor, tipodocumento, tema];
			objetivo = "cbSubtema";
			id = 5;
			// var como = dijit.byId('idActual');
			// como.attr('value',tema);
			// como.attr('focus',true);
			// console.debug(como.focusNode('clientLeft'));
			break;
	}

	console.debug(campo);
	console.debug('lstParam ' + lstParam);
	console.debug('lstValues ' + lstValues);

	mostrarDialogo();
	var info = new datosCombo(campo, lstParam, lstValues);
	dojo.xhrPost({
		url : '/normsearch/llenarCombo.htm',
		content : info,
		contentType : "application/x-www-form-urlencoded;charset=UTF-8",
		load : function(data, event) {
			console.debug('Resultados');
			var imag = dojo.byId('img' + id);
			imag.style.display = 'inline';
			console.debug('img' + id + ': ' + imag.style.display);
			var result = dojo.fromJson(data);
			console.debug(result.result);

			var elementos = [];
			elementos.push({
				name : 'TODOS'
			});
			dojo.forEach(result.result, function(item) {
				elementos.push({
					name : item
				});
			});
			console.debug('Elementos: ' + elementos);
			var options = new dojo.data.ItemFileWriteStore({
				data : {
					identifier : "name",
					items : elementos
				}
			});
			dijit.byId(objetivo).attr('store', options);
			dijit.byId(objetivo).attr('displayedValue', 'TODOS');
			imag.style.display = 'none';
			console.debug('img' + id + ': ' + imag.style.display);
		},
		error : function(data, event) {
			displayError(data, event);
		}
	});

	ocultarDialogo();
}

function obtenerValorEstatus() {
	var estatus = dijit.byId('cbEstatus').value;
	var valor = '';
	if (estatus == 'TODOS')
		valor = '*';
	else
		valor = estatus;
	return valor;
}

function obtenerValorEmisor() {
	var valor = '';
	var emisor = dijit.byId('cbEmisor').value;
	if (emisor == 'TODOS')
		valor = '*';
	else
		valor = emisor;
	return valor;
}

function obtenerValorTipodocumento() {
	var valor = '';
	var tipoDoc = dijit.byId('cbTipodocumento').value;
	if (tipoDoc == 'TODOS')
		valor = '*';
	else
		valor = tipoDoc;
	return valor;
}

function obtenerValorTema() {
	var valor = '';
	var tema = dijit.byId('cbTema').value;
	if (tema == 'TODOS')
		valor = '*';
	else
		valor = tema;
	return valor;
}

function obtenerValorSubtema() {
	var valor = '';
	var subTema = dijit.byId('cbSubtema').value;
	if (subTema == 'TODOS')
		valor = '*';
	else
		valor = subTema;
	return valor;
}

function busqueaAvanNormateca(valor) {
	console.debug('-------entro al busqueaAvanNormateca-------');
	var consulta;
	var flag = true;
	var flag2 = false;
	var flag3 = true;
	if (valor == null)
		consulta = dojo.byId('consulta').value;
	else
		consulta = valor;

	var lstParam = ['estatus', 'emisor', 'tipodocumento', 'tema', 'subtema'];
	var lstValues = [];
	lstValues.push(obtenerValorEstatus());
	lstValues.push(obtenerValorEmisor());
	lstValues.push(obtenerValorTipodocumento());
	lstValues.push(obtenerValorTema());
	lstValues.push(obtenerValorSubtema());
	for ( var i = 0; i < lstValues.length; i++) {
		if (lstValues[i] != '*')
			flag = false;
	}
	var date1, date2;
	var cadDate1, cadDate2;
	if (document.getElementById("cb").checked) {
		date1 = dijit.byId('date1').attr('value');
		date2 = dijit.byId('date2').attr('value');
		var dia1 = calcularDia(date1.getDate());
		var dia2 = calcularDia(date2.getDate());
		if (dia1 == "")
			cadDate1 = date1.getDate() + '/' + cacularMes(date1.getMonth())
					+ '/' + date1.getFullYear();
		else
			cadDate1 = dia1 + '/' + cacularMes(date1.getMonth()) + '/'
					+ date1.getFullYear();
		if (dia2 == "")
			cadDate2 = date2.getDate() + '/' + cacularMes(date2.getMonth())
					+ '/' + date2.getFullYear();
		else
			cadDate2 = dia2 + '/' + cacularMes(date2.getMonth()) + '/'
					+ date2.getFullYear();
		flag2 = false;
	} else {
		cadDate1 = '';
		cadDate2 = '';
		flag2 = true;
	}
	/*
	 * if(!validarConsulta(consulta)){ consulta ='*'; } else flag3 = false;
	 */
	consulta = validarCadena(consulta);
	if (consulta != null) {
		flag3 = false;
	} else {
		consulta = '*';
	}

	console.debug('flag ---------->' + flag);
	console.debug('flag2 ---------->' + flag2);
	console.debug('flag3 ---------->' + flag3);
	if (flag && flag2 && flag3) {
		alert('Favor de revisar los t\u00e9rminos empleados. S\u00f3lo se pueden utilizar letras, n\u00fameros y los siguientes s\u00edmbolos: *, /, \"  y %.');
		return;
	}
	mostrarDialogo();

	var orden = dijit.byId('cbOrden').attr('value');
	orden = orden.substring(0, 3);
	var value;
	switch (orden) {
		case 'Nom' :
			value = 'titulo';
			break;
		case 'Fec' :
			value = 'fechadof';
			break;
		case 'Emi' :
			value = 'emisor';
			break;
		case 'Tip' :
			value = 'tipodocumento';
			break;
		case 'Est' :
			value = 'estatus';
			break;
	}
	var cadenaValues = lstValues.join("-");
	console.debug('consulta ' + consulta);
	console.debug('lstParam ' + lstParam);
	console.debug('lstValues ' + lstValues);
	console.debug('date1 ' + cadDate1);
	console.debug('date2 ' + cadDate2);
	console.debug('orden ' + orden);
	console.debug('value ' + value);
	console.debug('cadenaValues ' + cadenaValues);

	var ruta = '/normsearch/Static/html/cu_ba_normatecaresult.html?consulta='
			+ escape(consulta) + '&param=' + lstParam + '&lstValues='
			+ escape(cadenaValues) + '&fech1=' + cadDate1 + '&fech2='
			+ cadDate2 + '&orden=' + value;
	console.debug(ruta);
	location.href = ruta;
}

function buscarEnter(event) {
	console.debug('buscarEnter');
	if (event.keyCode == dojo.keys.ENTER) {
		var consulta = dojo.byId('consulta').value;
		console.debug(consulta);
		busqueaAvanNormateca(consulta);
	}
}

function mostrarDialogo() {
	var dialogo = dijit.byId('diaMensaje');
	dialogo.show();
}

function ocultarDialogo() {
	var dialogo = dijit.byId('diaMensaje');
	setTimeout( function() {
		dialogo.hide();
	}, "2000");
	dialogo.attr('autofocus', false);
}

function crearCbOrdenar(divCb, idCb) {
	var elementosOriginal = new datosCbOrden();
	listaOrden = elementosOriginal;
	var lista = [];
	for ( var i = 0; i < elementosOriginal.length; i++) {		
		lista.push({
			name : elementosOriginal[i]
		});
	}
	var options = new dojo.data.ItemFileWriteStore({
		data : {
			identifier : "name",
			items : lista
		}
	});
	var myDijit = new dijit.form.ComboBox({
		id : idCb,
		value : 'Nombre Disposición',
		store : options,
		searchAttr : 'name'
	});
	dojo.byId(divCb).appendChild(myDijit.domNode);
}

function eliminarCbOrdenar(elemento) {
	console
			.debug('******************** eliminarCbOrdenar ********************')
	var combo = dijit.byId('cbOrden');
	var lista = [];
	var nuevaLista = [];
	for ( var i = 0; i < listaOrden.length; i++) {
		if (listaOrden[i] != elemento) {
			console.debug('El elemento agregado fue: ' + listaOrden[i]);
			lista.push({
				name : listaOrden[i]
			});
			nuevaLista.push(listaOrden[i]);
		} else {
			console.debug('El elemento eliminado fue: ' + elemento);
		}
	}
	listaOrden = nuevaLista;
	var options = new dojo.data.ItemFileWriteStore({
		data : {
			identifier : "name",
			items : lista
		}
	});
	combo.attr('store', options);
	combo.attr('value', nuevaLista[0]);
}

function agregarCbOrdenar(elemento) {
	console.debug('******************** agregarCbOrdenar ********************')
	var combo = dijit.byId('cbOrden');
	var lista = [];
	var flag = true;
	for ( var i = 0; i < listaOrden.length; i++) {
		console.debug('Los elementos son: ' + listaOrden[i]);
		lista.push({
			name : listaOrden[i]
		});
		if (listaOrden[i] == elemento) {
			console
					.debug('El elemento ya esta en lista no se agrega ------->' + elemento);
			flag = false;
		}
	}
	if (flag) {
		listaOrden.unshift(elemento);
		lista.push({
			name : elemento
		});
		var options = new dojo.data.ItemFileWriteStore({
			data : {
				identifier : "name",
				items : lista
			}
		});
		combo.attr('store', options);
		combo.attr('value', listaOrden[0]);
	}
}
