var xmlHttp = createXMLHttpObject();
var cache = new Array();
var arrMeses = new Array();
var mostrarErrores = true;
var serverScript = "ajax.php";
var totalDias = 0;
var semana = 0;
var foliosAgregados = new Array();
var lugaresAgregados = new Array();
//var lugaresFolios = new Array(new Array(), new Array());
var totalEventosEjecutados = 0;
var empleadoEncontrado = false;
var activarGuardado = false;
var cache = new Array();

function mostrarFormularioIngreso(){
	if($('#formulario_ingreso').css('display') == 'none')
		$('#formulario_ingreso').fadeIn('500');
	else
		$('#formulario_ingreso').fadeOut('500');
}

function verPoliticas(tipo){
	if(tipo == "internas")
		window.open("politicas_internas.php", "politicas_internas", "width=800, height=600, toolbar=no, menubar=no, location=no, status=no, directories=no");
	if(tipo == "externas")
		window.open("politicas_externas.php", "politicas_externas", "width=800, height=600, toolbar=no, menubar=no, location=no, status=no, directories=no");
		
	document.getElementById("checkbox_aceptar").disabled = false;
}

function agregarInputText(id, dia, nombre_dia, mes){
	var celda = document.getElementById(id);
	obtenerSemana(celda.id.split("_")[1], celda, dia, nombre_dia, mes);
}

function cerrarInputText(id, dia, nombre_dia, mes){
	var celda = document.getElementById(id);
	var d = id.split("_")[1];
	celda.innerHTML = '<a href="#" onclick="agregarInputText(\'' + dia + '_' + d + '\', \'' + dia + '\', ' + nombre_dia + ', ' + mes + '); return false">' + d + '</a>';
	calcularDiasSemana();
}

function createXMLHttpObject(){
	var xmlHttp;
	
	try{
		xmlHttp = new XMLHttpRequest();
	}
	catch(e){
		var xmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
								    'MSXML2.XMLHTTP.5.0',
								    'MSXML2.XMLHTTP.4.0',
								    'MSXML2.XMLHTTP.3.0',
								    'MSXML2.XMLHTTP',
								    'Microsoft.XMLHTTP');
		
		for(var i = 0; i < xmlHttpVersions.length; i++){
			try{
				xmlHttp = new ActiveXObject(xmlHttpVersions[i]);
			}
			catch(e){}
		}
	}
	
	if(!xmlHttp && mostrarErrores)
		alert("Error al crear el objeto XMLHttpRequest()");
	else{
		return xmlHttp;
	}
}

function cambiar_mes(oSelect){
	if(xmlHttp){
		if(oSelect){
			var oSIndex = oSelect.selectedIndex;
			var oSValue = oSelect.options[oSIndex].value;
			var oSText = oSelect.options[oSIndex].text;
			cache.push("mes=" + oSValue);
			arrMeses.push(oSelect.id);
		}
		try{
			if((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) && cache.length > 0){
				var cacheItem = cache.shift();
				oMes = arrMeses.shift();
				xmlHttp.open("GET"," ajax.php" + '?accion=meses&' + cacheItem, true);
				xmlHttp.onreadystatechange = function(){
					if(xmlHttp.readyState == 4){
						if(xmlHttp.status == 200){
							try{
								var respuesta = xmlHttp.responseText;
								if(respuesta.indexOf("ERRNO") >= 0 || respuesta.indexOf("errno:") >= 0 || respuesta.indexOf("error") >= 0 || respuesta.length == 0)
									throw(respuesta.length == 0 ? "Error de servidor." : respuesta);
																
								var oDia = document.getElementById('dia_nac');
								oDia.disabled = true;
								oDia.length = 0;
								for(var i = 1; i <= respuesta; i++){
									oDia.options[i - 1] = new Option(i);
									oDia.options[i - 1].value = i;
								}
								oDia.disabled = false;
								if(cache.length > 0)
									setTimeout("cambiar_mes()", 1000);
							}
							catch(e){
								if(mostrarErrores)
									alert("ERROR AL CARGAR LOS DATOS " + e.toString());
							}
						}
						else{
							if(mostrarErrores)
								alert(xmlHttp.statusText);
						}
					}
				};
				xmlHttp.send(null);
			}
		}
		catch(e){
			if(mostrarErrores)
				alert("ERROR AL CARGAR EL MES " + e.toString());
		}
	}
	return true;
}

function checarTeclas(e){
	var tecla = (document.all) ? e.keyCode : e.which;
	//alert(tecla);
	if(tecla== 9) return true;
	if(tecla== 190) return true;
	if(tecla== 8) return true;
	if(tecla== 46) return true;
	if(tecla>= 35 && tecla <= 39) return true;
	if(tecla>= 96 && tecla <= 105) return true;
	patron = /[0-9]/;
	return patron.test(String.fromCharCode(tecla));
}

function agregarGuion(e){
	if(window.event)
		var oInput = window.event.srcElement;
	else
		var oInput = e.target;
	
	var tecla = (document.all) ? e.keyCode : e.which;
	if(tecla != 8 && (oInput.value.length == 3 || oInput.value.length == 7)){
		oInput.value += '-';
	}
}

function enableRegisterButton(checkbox){
	var button = document.getElementById('accion');
	var filled = checkFilledForm();
	
	if(filled && checkbox.checked)
		button.disabled = false;
	else
		button.disabled = true;
}

function checkFilledForm(){
	var frmElements = document.forms['formulario_registro'].elements;
	var filled = false;
	var numCheckboxes = 8;
	var numCheckboxesChecked = 0;
	for(var i = 0; i < frmElements.length; i++){
		try{
			if(frmElements[i].type == 'text' && (frmElements[i].name != 'tel_recados' && frmElements[i].name != 'tel_celular' && frmElements[i].name != 'facebook' && frmElements[i].name != 'twitter')){				
				if(frmElements[i].type == 'text'){
					if(frmElements[i].value == ''){
						filled = false;
						break;
					}
					else{
						filled = true;
					}
				}
			}
		}
		catch(e){
			if(mostrarErrores)
				alert("Error al tratar de checar el llenado del formulario\n" + e.toString());
		}
	}
	return filled;
}

function verificarDatos(frm, camposOpcionales){
	var frmElements = document.getElementById(frm).elements;
	var error = false;
	var sErrSpanId;
	var oErrSpan;
	var sError = '';
	var oDivError;
	var bNombreA = bNombreB = '';
	
	//Checa los cuadros de texto
	for(var i = 0; i < frmElements.length; i++){
		try{
			sErrSpanId = 'err_' + frmElements[i].id;
			oErrSpan = document.getElementById(sErrSpanId);
			if(frmElements[i].type == 'text'){
				//alert(frmElements[i].name);
				if(buscarCamposOpcionales(frmElements[i].name, camposOpcionales)){
					continue;
				}
				if(frmElements[i].value == ''){
					error = true;
					oErrSpan.style.display = 'inline';
					
					if(frmElements[i].title != '')
						oErrSpan.innerHTML = '*';
				}
				else{
					oErrSpan.style.display = 'none';
					oErrSpan.innerHTML = '';
				}
			}
			 if(frmElements[i].type == 'checkbox'){
				//Checar checkboxes
				if(frmElements[i].value == 0){
					error = true;
					oErrSpan.style.display = 'inline';
					
					if(frmElements[i].title != '')
						oErrSpan.innerHTML = '*';
				}
				else{
					oErrSpan.style.display = 'none';
					oErrSpan.innerHTML = '';
				}
			}
		}
		catch(e){
			if(mostrarErrores)
				alert("Error al validar los datos (text)\n" + e.toString());
		}
	}
	
	try{
		var arrSelect = document.getElementsByTagName('select');
		for(var i = 0; i < arrSelect.length; i++){
			if(buscarCamposOpcionales(arrSelect[i].name, camposOpcionales)){
				continue;
			}
			if(arrSelect[i].options[arrSelect[i].selectedIndex].value == -1){
				//alert('select ' + arrSelect[i].name + ' ' + arrSelect[i].id);
				sErrSpanId = arrSelect[i].id;
				sErrSpanId = 'err_' + sErrSpanId;
				oErrSpan = document.getElementById(sErrSpanId);
				oErrSpan.style.display = 'inline';
				oErrSpan.innerHTML = '*';
				error = true;
			}
			else{
				if(arrSelect[i].name != 'lugar_folio'){
					sErrSpanId = arrSelect[i].id;
					sErrSpanId = 'err_' + sErrSpanId;
					oErrSpan = document.getElementById(sErrSpanId);	
					oErrSpan.style.display = 'none';
					oErrSpan.innerHTML = '';
				}
			}
		}
			
		/* var txtArea = document.getElementsByTagName('textarea');
		for(var i = 0; i < txtArea.length; i++){
			if(txtArea[i].value.length == 0 && buscarCamposOpcionales(frmElements[i].name, camposOpcionales)){
				sErrSpanId = txtArea[i].id;
				sErrSpanId = 'err_' + sErrSpanId;
				oErrSpan = document.getElementById(sErrSpanId);
				oErrSpan.style.display = 'inline';
				oErrSpan.innerHTML = '*';
				error = true;
			}
			else{
				sErrSpanId = txtArea[i].id;
				sErrSpanId = 'err_' + sErrSpanId;
				oErrSpan = document.getElementById(sErrSpanId);
				oErrSpan.style.display = 'none';
				oErrSpan.innerHTML = '';
			}
		}  */
	}
	catch(e){
		if(mostrarErrores)
			alert("Error al validar los datos\n" + e.toString());
	}
	return !error;
}

function buscarCamposOpcionales(campo, campos){
	var encontrado = false;
	for(var n = 0; n < campos.length; n++){
		if(campo == campos[n]){
			encontrado = true;
			break;
		}
	}
	
	return encontrado;
}

function buscarEmpleadoTeclado(e){
	var tecla = (document.all) ? e.keyCode : e.which;
	if(tecla == 13)
		buscarEmpleado();
}

function buscarEmpleado(){
	if(xmlHttp && document.getElementById('no_empleado').value){
		$('#info_personal').fadeIn('500');
		//$('#info_personal').fadeOut('500');
		var noEmpleado = document.getElementById('no_empleado');
		var infoNombre = document.getElementById('info_nombre');
		document.getElementById('info_direccion').innerHTML = '';
		document.getElementById('info_telefonos').innerHTML = '';
		document.getElementById('info_email').innerHTML = '';
		document.getElementById('info_rfc').innerHTML = '';
		document.getElementById('info_cuenta').innerHTML = '';
		document.getElementById('info_plaza').innerHTML = '';
		document.getElementById('info_error').innerHTML = '';
		infoNombre.innerHTML = "Buscando empleado...";
		try{
			if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0 && noEmpleado.value != ''){
				xmlHttp.open("GET", serverScript + '?accion=buscar_empleado&id=' + noEmpleado.value, true);
				xmlHttp.onreadystatechange = function(){
					if(xmlHttp.readyState == 4){
						if(xmlHttp.status == 200){
							var respuesta = xmlHttp.responseText;
							if(respuesta.indexOf("ERRNO") >= 0 || respuesta.indexOf("errno:") >= 0 || respuesta.indexOf("error") >= 0 || respuesta.length == 0)
								throw(respuesta.length == 0 ? "Error de servidor." : respuesta);
							
							respuesta = xmlHttp.responseXML;
							if(!respuesta || !respuesta.documentElement)
								throw("Estructura del archivo XML invalida!\n" + respuesta);
							
							var rootNodeName = respuesta.documentElement.nodeName;
							if(rootNodeName == "parsererror")
								throw("Estructura del archivo XML invalida!");
							
							noEmpleado.value = '';
							mostrarInfoEmpleado(respuesta);
						}
						else{
							if(mostrarErrores)
								alert(xmlHttp.statusText);
						}
					}
				}
				xmlHttp.send(null);
			}
		}
		catch(e){
			if(mostrarErrores)
				alert(e.toString());
		}
	}
}

function mostrarInfoEmpleado(respuesta){
	var xmlRoot = respuesta.documentElement;
	var id = xmlRoot.getElementsByTagName('id');
	var id_num = xmlRoot.getElementsByTagName('id_num');
	var nombre = xmlRoot.getElementsByTagName('nombre');
	var direccion = xmlRoot.getElementsByTagName('direccion');
	var telefonoLocal = xmlRoot.getElementsByTagName('telefono_local');
	var telefonoRecados = xmlRoot.getElementsByTagName('telefono_recados');
	var telefonoMovil = xmlRoot.getElementsByTagName('telefono_movil');
	var email = xmlRoot.getElementsByTagName('email');
	var rfc = xmlRoot.getElementsByTagName('rfc');
	var noCuenta = xmlRoot.getElementsByTagName('no_cuenta');
	var plaza = xmlRoot.getElementsByTagName('plaza');
	
	var infoNombre = document.getElementById('info_nombre');
	var infoDireccion = document.getElementById('info_direccion');
	var infoTelefonos = document.getElementById('info_telefonos');
	var infoEmail = document.getElementById('info_email');
	var infoRFC = document.getElementById('info_rfc');
	var infoCuenta = document.getElementById('info_cuenta');
	var infoPlaza = document.getElementById('info_plaza');
	var infoError = document.getElementById('info_error');
	
	if(id[0].firstChild.data == -1){
		infoError.innerHTML = "El N&uacute;mero de empleado no existe en la Base de Datos";
		infoNombre.style.display = 'none';
		infoDireccion.style.display = 'none';
		infoTelefonos.style.display = 'none';
		infoEmail.style.display = 'none';
		infoRFC.style.display = 'none';
		infoCuenta.style.display = 'none';
		infoPlaza.style.display = 'none';
		empleadoEncontrado = false;
	}
	else{
		infoNombre.style.display = 'inline';
		infoDireccion.style.display = 'inline';
		infoTelefonos.style.display = 'inline';
		infoEmail.style.display = 'inline';
		infoRFC.style.display = 'inline';
		infoCuenta.style.display = 'inline';
		infoPlaza.style.display = 'inline';
		infoError.innerHTML = '';
		infoNombre.innerHTML = '<span style="font-weight: bold; ">Nombre: </span>' + nombre[0].firstChild.data + '<br />';
		infoNombre.style.textTransform = 'capitalize';
		
		infoDireccion.innerHTML =  '<span style="font-weight: bold; ">Direcci&oacute;n: </span>' + direccion[0].firstChild.data + '<br />';
		infoDireccion.style.textTransform = 'capitalize';
		
		var tels = '';
		if(telefonoLocal[0].firstChild.data)
			tels = telefonoLocal[0].firstChild.data;
		if(telefonoRecados[0].firstChild.data){
			if(tels != '')
				tels += ', ' + telefonoRecados[0].firstChild.data;
			else
				tels = telefonoRecados[0].firstChild.data;
		}
		if(telefonoMovil[0].firstChild.data){
			if(tels != '')
				tels += ', ' + telefonoMovil[0].firstChild.data;
			else
				tels = telefonoMovil[0].firstChild.data;
		}
		infoTelefonos.innerHTML =  '<span style="font-weight: bold; ">T&eacute;lefonos: </span>' + tels + '<br />';
		
		infoEmail.innerHTML =  '<span style="font-weight: bold; ">Correo: </span>' + email[0].firstChild.data + '<br />';
		infoRFC.innerHTML = '<span style="font-weight: bold; ">R.F.C.: </span>' +  rfc[0].firstChild.data + '<br />';
		infoCuenta.innerHTML =  '<span style="font-weight: bold; ">No. Cuenta: </span>' + noCuenta[0].firstChild.data + '<br />';
		var strPlaza = '';
		
		switch(parseInt(plaza[0].firstChild.data)){
			case 1:
				strPlaza = 'Toluca';
			break;
			case 2:
				strPlaza = 'Acapulco';
			break;
			case 4:
				strPlaza = 'Cuernavaca';
			break;
		}
		infoPlaza.innerHTML = '<span style="font-weight: bold; ">Plaza: </span>' + strPlaza + '<br />';
		
		document.getElementById('evt_empleado').value = id_num[0].firstChild.data;
		document.getElementById('plaza').selectedIndex = plaza[0].firstChild.data;
		empleadoEncontrado = true;
		document.getElementById('folio').focus();
	}
	
	//$('#info_personal').fadeIn('500');
}

function mostrarAyuda(opcion){
	if(opcion == 'categoria'){
		if($('#ayuda_categoria').css('display') == 'none')
			$('#ayuda_categoria').fadeIn('500');
		else
			$('#ayuda_categoria').fadeOut('500');
	}
	else if(opcion == 'canal'){
		if($('#ayuda_canal').css('display') == 'none')
			$('#ayuda_canal').fadeIn('500');
		else
			$('#ayuda_canal').fadeOut('500');
	}
}

function calcularDiasSemana(){
	var tDias = calcularTotalDias();
	document.getElementById('total_dias').value = tDias;
	if(tDias == 0){
		document.getElementById('semana_anio').value = 0;
		semana = 0;
	}
}

function calcularTotalDias(){
	var dias = document.getElementsByName('dias[]');
	totalDias = 0;
	for(var i = 0; i < dias.length; i++){
		totalDias++
	}
	
	return totalDias;
}

function calcularTotalDiasEvento(s){
	if(xmlHttp){
		try{
			if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0 && noEmpleado.value != ''){
				var plaza = document.getElementById('plaza');
				//alert('accion=calcular_dias_evento&semana=' + s + '&anio=' + document.getElementById('anio').value + '&p=' + plaza.options[plaza.selectedIndex].value);
				xmlHttp.open("GET", serverScript + '?accion=calcular_dias_evento&semana=' + s + '&anio=' + document.getElementById('anio').value + '&p=' + plaza.options[plaza.selectedIndex].value, true);
				xmlHttp.onreadystatechange = function(){
					if(xmlHttp.readyState == 4){
						if(xmlHttp.status == 200){
							var respuesta = xmlHttp.responseText;
							//alert(respuesta);
							if(respuesta.indexOf("ERRNO") >= 0 || respuesta.indexOf("errno:") >= 0 || respuesta.indexOf("error") >= 0 || respuesta.length == 0)
								throw(respuesta.length == 0 ? "Error de servidor." : respuesta);
							
							//document.getElementById('total_dias_semana').value = respuesta;
						}
						else{
							if(mostrarErrores)
								alert(xmlHttp.statusText);
						}
					}
				}
				xmlHttp.send(null);
			}
		}
		catch(e){
			if(mostrarErrores)
				alert(e.toString());
		}
	}
}

function obtenerSemana(dia_semana, celda, dia, nombre_dia, mes){
	if(document.getElementById('semana_anio').value == 0 || (semana == document.getElementById('semana_anio').value)){
		if(xmlHttp){
			try{
				if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0 && dia != ''){
					xmlHttp.open("GET", serverScript + '?accion=calcular_semana&dia=' + dia_semana + '&mes=' + mes, true);
					xmlHttp.onreadystatechange = function(){
						if(xmlHttp.readyState == 4){
							if(xmlHttp.status == 200){
								var respuesta = xmlHttp.responseText;
								//alert(respuesta);
								if(respuesta.indexOf("ERRNO") >= 0 || respuesta.indexOf("errno:") >= 0 || respuesta.indexOf("error") >= 0 || respuesta.length == 0)
									throw(respuesta.length == 0 ? "Error de servidor." : respuesta);
									
								if(document.getElementById('semana_anio').value == 0){
									document.getElementById('semana_anio').value = respuesta;
									semana = respuesta;
									//calcularTotalDiasEvento(semana);
								}
								if(semana == respuesta){
									celda.innerHTML = '<input type="hidden" name="dias[]" value="' + nombre_dia + '" /><img src="img/iconos/cerrar.png" style="margin-left: 5px; cursor: pointer" onclick="cerrarInputText(\'' + celda.id + '\', \'' + dia + '\', ' + nombre_dia + ', ' + mes + ')" />' ;
									calcularDiasSemana();
								}
							}
							else{
								if(mostrarErrores)
									alert(xmlHttp.statusText);
							}
						}
					}
					xmlHttp.send(null);
				}
			}
			catch(e){
				if(mostrarErrores)
					alert(e.toString());
			}
		}
	}
}

function resetearFormulario(frm){
	if(frm == 'formulario_eventos'){
		document.getElementById('semana_anio').value = 0;
		semana = 0;
		
		$('#tb_mes').fadeOut('500');
		$('#info_personal').fadeOut('500');
		
		var dias = document.getElementsByName('dias[]');
		for(var i = 0; i < dias.length; i++){
			;
		}
		crearCalendario();
		document.getElementById('evt_empleado').value = '';
		document.getElementById('evt_folio').value = '';
		document.getElementById('evt_lugar').value = '';
		document.getElementById('semana_anio').value = 0;
		
		totalDias = 0;
		semana = 0;
		foliosAgregados = new Array();
		lugaresAgregados = new Array();
		//lugaresFolios = new Array(new Array(), new Array());
		totalEventosEjecutados = 0;
		empleadoEncontrado = false;
	}
}

function mostrarCalendario(){
	if($('#tb_mes').css('display') == 'none')
		$('#tb_mes').fadeIn('500');
}

function agregarFolioTeclado(e){
	var tecla = (document.all) ? e.keyCode : e.which;
	if(tecla == 13)
		agregarFolio();
}

function agregarFolio(){
	var folio = document.getElementById('folio');
	var divFolios = document.getElementById('folios');
	
	if(folio.value != 0 || folio.value != ''){
		if($('#folios').css('display') == 'none')
			$('#folios').fadeIn('500');
		if(buscarFolio(folio.value) == -1){
			divFolios. innerHTML += '<input type="hidden" name="folios[]" value="' + folio.value + '" id="h_folio_" ' + folio.value + '" />';
			divFolios. innerHTML += '<span style="float: left; margin: 0 0 5px 5px; padding: 5px; background-color: #E8EBF2; display: none" id="folio_' + folio.value + '"><span style="margin-right: 5px;">' + folio.value + '</span><a href="#" onclick="eliminarFolio(\'folio_' + folio.value + '\')" /><img src="img/iconos/cerrar.png" /></a></span>';
			foliosAgregados.push(folio.value);
			$('#folio_' + folio.value).fadeIn('500');
			
			var selectFolios = document.getElementById('lugar_folio');
			var option = document.createElement('option');
			option.text = folio.value;
			option.value = folio.value;
			selectFolios.options[selectFolios.length] = option;
			folio.value = '';
		}
	}
}

function eliminarFolio(folio){
	var pos = buscarFolio(folio.split("_")[1]);
	foliosAgregados.splice(pos, 1);
	var selectFolios = document.getElementById('lugar_folio');
	selectFolios.remove(pos);
	
	var folios = buscarFolioEnLugares(folio.split("_")[1]);
	var divLugares = document.getElementById('lugares');
	//alert("longitud folios: " + folios.length);
	if(folios.length > 0){
		for(var i = 0; i < folios.length; i++){
			//alert("folio: " + folios[i]);
			var lugar = lugaresAgregados[folios[i]];
			//alert("lugar: " + lugar);
			divLugares.removeChild(document.getElementById(lugar));
			//alert(divLugares.innerHTML);
		}
		for(var i = 0; i < folios.length; i++){
			lugaresAgregados.splice(0, 1);
			//alert('arreglo: ' + lugaresAgregados);
		}
	}
	if(lugaresAgregados.length == 0)
		document.getElementById('lugares').style.display = 'none';
	$('#' + folio).fadeOut(500, ocultarFolios);
}

function ocultarFolios(){
	if(foliosAgregados.length == 0){
		document.getElementById('folios').style.display = 'none';
	}
}

function agregarLugarTeclado(e){
	var tecla = (document.all) ? e.keyCode : e.which;
	if(tecla == 13)
		agregarLugar();
}

function agregarLugar(){
	var lugar = document.getElementById('lugar');
	var divLugares = document.getElementById('lugares');
	var selectLugares = document.getElementById('lugar_folio');
	
	if(lugar.value != '' && selectLugares.options[selectLugares.selectedIndex].value != ''){
		if($('#lugares').css('display') == 'none')
			$('#lugares').fadeIn('500');
		
		var numEspacios = lugar.value.split(" ");
		var lugarId = '';
		if(numEspacios.length > 0){
			lugarId = numEspacios.join("_");
		}
		else{
			lugarId = lugar.value;
		}
		//alert('id del lugar: ' + lugarId);
		if(buscarLugar(lugarId + '_' + selectLugares.options[selectLugares.selectedIndex].value) == -1){
			//alert('folio agregado: ' + selectLugares.options[selectLugares.selectedIndex].value);
			divLugares. innerHTML += '<span style="float: left; margin: 0 0 5px 5px; padding: 5px; background-color: #E8EBF2; display: none" id="' + lugarId + '_' + selectLugares.options[selectLugares.selectedIndex].value + '"><a href="#" onclick="mostrarInfoEvento(\'' + lugarId + '_' + selectLugares.options[selectLugares.selectedIndex].value + '\', \'' + lugar.value.toUpperCase() + '\', ' + selectLugares.options[selectLugares.selectedIndex].value + ')"><span style="margin-right: 5px;">Lugar: ' + lugar.value.toUpperCase() + ' Folio: ' + selectLugares.options[selectLugares.selectedIndex].value + '</span></a><a href="#" onclick="eliminarLugar(\'' + lugarId + '_' + selectLugares.options[selectLugares.selectedIndex].value + '\')" /><img src="img/iconos/cerrar.png" /></a></span>';
			//alert(divLugares.innerHTML);
			lugaresAgregados.push(lugarId + '_' + selectLugares.options[selectLugares.selectedIndex].value);
			/* var arrayLugar = lugaresFolios[0];
			var arrayFolios = lugaresFolios[1];
			arrayLugar.push(lugarId);
			arrayFolios.push(selectLugares.options[selectLugares.selectedIndex].value);
			lugaresFolios = new Array(arrayLugar, arrayFolios); */
			lugar.value = '';
			//alert('arreglo: ' + lugaresAgregados);
			$('#' + lugarId + '_' + selectLugares.options[selectLugares.selectedIndex].value).fadeIn('500');
		}
	}
}

function buscarFolio(folio){
	var encontrado = -1;
	for(var i = 0; i < foliosAgregados.length; i++){
		if(foliosAgregados[i] == folio){
			encontrado = i;
			break;
		}
	}
	return encontrado;
}

function buscarLugar(lugar){
	//alert(lugar);
	var encontrado = -1;
	for(var i= 0; i < lugaresAgregados.length; i++){
		if(lugaresAgregados[i] == lugar){
			encontrado = i;
			break;
		}
	}
	//alert(encontrado);
	return encontrado;
	/* alert(lugar)
	var l = document.getElementById(lugar);
	alert(l);
	if(l == null || l == undefined)
		return true;
	else
		return false; */
}

function eliminarLugar(lugar){
	//alert(lugar);
	var pos = buscarLugar(lugar);
	lugaresAgregados.splice(pos, 1);
	var divLugares = document.getElementById('lugares');
	divLugares.removeChild(document.getElementById(lugar));
	//alert(lugaresAgregados);
	$('#' + lugar).fadeOut(500, ocultarLugares);
}

function ocultarLugares(){
	if(lugaresAgregados.length == 0){
		document.getElementById('lugares').style.display = 'none';
	}
}

function buscarFolioEnLugares(folio){
	var encontrado = new Array();
	
	//Buscando los folios
	for(var i = 0; i < lugaresAgregados.length; i++){
		var f = lugaresAgregados[i].split("_");
		f = f[f.length - 1];
		//alert(f + ' ' + folio);
		if(f == folio){
			encontrado.push(i);
		}
	}
	//alert("encontrados en: " + encontrado);
	return encontrado;
}

function mostrarInfoEvento(lugar, titulo, folio){
	//alert(lugar);
	var pos = buscarLugar(lugar);
	lugaresAgregados.splice(pos, 1);
	var divLugares = document.getElementById('lugares');
	divLugares.removeChild(document.getElementById(lugar));
	//alert(lugaresAgregados);
	
	$('#' + lugar).fadeOut(500, ocultarLugares);
	
	$('#info_evento').fadeIn(500);
	var cabecera = $('#info_evento' + ' h3')[0];
	cabecera.innerHTML = 'Lugar: ' + titulo + ' Folio: ' + folio;
	totalEventosEjecutados++;
	document.getElementById('evt_lugar').value = titulo;
	document.getElementById('evt_folio').value = folio;
	activarGuardado = true;
}

function registrarEvento(frm){
	var error = verificarDatos(frm, ['folio', 'no_empleado', 'total_dias', 'lugar', 'lugar_folio']);
	//alert(semana + ' ' + error + ' ' + activarGuardado);
	if(error && semana != 0 && empleadoEncontrado && activarGuardado){
		document.getElementById('accion').disabled = true;
		enviarDatosRegistro(frm);
	}
	else{
		if(mostrarErrores){
			alert("Error al enviar los datos");
		}
	}
}

function enviarDatosRegistro(frm){
	if(xmlHttp){
		//Obtener los datos del formulario
		var idEmpleado = document.getElementById('evt_empleado').value;
		var folio = document.getElementById('evt_folio').value;
		var lugar = document.getElementById('evt_lugar').value;
		var categoria = document.getElementById('categoria').options[document.getElementById('categoria').selectedIndex].value;
		var plaza = document.getElementById('plaza').options[document.getElementById('plaza').selectedIndex].value;
		var canal = document.getElementById('canal').options[document.getElementById('canal').selectedIndex].value;
		var total_dias = document.getElementById('total_dias').value;
		//var total_dias_semana = document.getElementById('total_dias_semana').value;
		var campania = document.getElementById('campania').value;
		var periodo = document.getElementById('periodo').value;
		var dias = document.getElementsByName('dias[]');
		var smn = document.getElementById('semana_anio').value;
		var diasSeleccionados = '';
		
		for(var i = 0; i < dias.length; i++){
			if(i == 0)
				diasSeleccionados += dias[i].value;
			else
				diasSeleccionados += ':' + dias[i].value;
		}
		
		var queryString = 'id=' + idEmpleado + '&folio=' + folio + '&lugar=' + lugar + '&categoria=' + categoria + '&canal=' + canal + '&total_dias=' + total_dias + '&campania=' + campania + '&plaza=' + plaza + '&periodo=' + periodo + '&semana=' + smn;
		queryString += '&dias=' + diasSeleccionados;
		//alert(queryString);
		try{
			if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
				xmlHttp.open("POST", serverScript + '?accion=registrar_evento', true);
				xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlHttp.onreadystatechange = function(){
					if(xmlHttp.readyState == 4){
						if(xmlHttp.status == 200){
							var respuesta = xmlHttp.responseText;
							alert(respuesta);
							if(respuesta.indexOf("ERRNO") >= 0 || respuesta.indexOf("errno:") >= 0 || respuesta.indexOf("error") >= 0 || respuesta.length == 0)
								throw(respuesta.length == 0 ? "Error de servidor." : respuesta);
							
							if(respuesta == 'Evento agregado' || respuesta == 'Activacion agregada'){
								semana = 0;
								activarGuardado = false;
								document.getElementById('accion').disabled = false;
								//empleadoEncontrado = false;
								/* document.getElementById('plaza').selectedIndex = 0;
								document.getElementById('categoria').selectedIndex = 0;
								document.getElementById('canal').selectedIndex = 0;
								document.getElementById('campania').value = '';
								document.getElementById('periodo').value = ''; */
								document.getElementById('semana_anio').value = 0;
								document.getElementById('total_dias').value = '';
								//alert("semana: " + semana + ' ' + activarGuardado);
								var divMes = document.getElementById('mes');
								divMes.removeChild(document.getElementById('tb_mes'));
								crearCalendario();
								$('#info_evento').fadeOut(500);
								//alert(document.getElementsByName('dias[]').length);
							}
						}
						else{
							if(mostrarErrores)
								alert(xmlHttp.statusText);
						}
					}
				}
				xmlHttp.send(queryString);
			}
		}
		catch(e){
			if(mostrarErrores)
				alert(e.toString());
		}
	}
}

function crearCalendario(){
	if(xmlHttp){
		try{
			if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
				xmlHttp.open("GET", serverScript + '?accion=crear_mes', true);
				xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlHttp.onreadystatechange = function(){
					if(xmlHttp.readyState == 4){
						if(xmlHttp.status == 200){
							var respuesta = xmlHttp.responseText;
							//alert(respuesta);
							if(respuesta.indexOf("ERRNO") >= 0 || respuesta.indexOf("errno:") >= 0 || respuesta.indexOf("error") >= 0 || respuesta.length == 0)
								throw(respuesta.length == 0 ? "Error de servidor." : respuesta);
								
							document.getElementById('mes').innerHTML = respuesta;
						}
						else{
							if(mostrarErrores)
								alert(xmlHttp.statusText);
						}
					}
				}
				xmlHttp.send(null);
			}
		}
		catch(e){
			if(mostrarErrores)
				alert(e.toString());
		}
	}
}


function mostrarCalendarioPersonal(no_empleado, activacion){
	if($('#calendario_' + no_empleado + "_" + activacion).css('display') == 'none')
		$('#calendario_' + no_empleado + "_" + activacion).fadeIn('500');
	else
		$('#calendario_' + no_empleado + "_" + activacion).fadeOut('500');
}

function mostrarEventosADetalle(evento, semana, anio, plaza){
	window.open("vista_detallada_eventos.php?opc=ver&evt=" + evento + "&smn=" + semana + "&anio=" + anio + "&plz=" + plaza, "vista_detallada_eventos", "");
}

function calcularImporte(i){
	var salarios = document.getElementsByName('salarios[]');
	var importes = document.getElementsByName('importes[]');
	var totales = document.getElementsByName('totales[]');
	var dias = document.getElementsByName('dias_activados[]');
	
	importes[i].value = dias[i].value * salarios[i].value;
	totales[i].value = importes[i].value;
	calcularSubtotal();
}

function agregarIngresos(i){
	var ingresos = document.getElementsByName('ingresos[]');
	var totales = document.getElementsByName('totales[]');
	totales[i].value = parseFloat(totales[i].value) + parseFloat(ingresos[i].value);
	calcularIngresos();
}

function restarDeducciones(i){
	var deducciones = document.getElementsByName('deducciones[]');
	var totales = document.getElementsByName('totales[]');
	totales[i].value = parseFloat(totales[i].value) - parseFloat(deducciones[i].value);
	calcularDeducciones();
}

function aplicarTodos(cancelar){
	var salarios = document.getElementsByName('salarios[]');
	var importes = document.getElementsByName('importes[]');
	var totales = document.getElementsByName('totales[]');
	var dias = document.getElementsByName('dias_activados[]');
	if(cancelar){
		for(var i = 1; i < salarios.length; i++){
			salarios[i].value = '';
			importes[i].value = '';
			totales[i].value = '';
		}
	}
	else{
		var salarioPrincipal = salarios[0].value;
		for(var i = 1; i < salarios.length; i++){
			salarios[i].value = salarioPrincipal;
			importes[i].value = dias[i].value * salarios[i].value;
			totales[i].value = importes[i].value;
		}
	}
	calcularSubtotal();
}

function calcularSubtotal(){
	var importes = document.getElementsByName('importes[]');
	var subtotal = 0;
	for(var i = 0; i < importes.length; i++){
		if(importes[i].value != '')
			subtotal += parseFloat(importes[i].value);
	}
	document.getElementById('subtotal').value = subtotal;
	calcularTotal();
}

function calcularTotal(){
	var totales = document.getElementsByName('totales[]');
	var total = 0;
	for(var i = 0; i < totales.length; i++){
		if(totales[i].value != '')
			total += parseFloat(totales[i].value);
	}
	document.getElementById('total').value = total;
}

function calcularIngresos(){
	var ingresos = document.getElementsByName('ingresos[]');
	var total = 0;
	for(var i = 0; i < ingresos.length; i++){
		if(ingresos[i].value != '')
			total += parseFloat(ingresos[i].value);
	}
	document.getElementById('total_ingresos').value = total;
	calcularTotal();
}

function calcularDeducciones(){
	var deducciones = document.getElementsByName('deducciones[]');
	var total = 0;
	for(var i = 0; i < deducciones.length; i++){
		if(deducciones[i].value != '')
			total += parseFloat(deducciones[i].value);
	}
	document.getElementById('total_deducciones').value = total;
	calcularTotal();
}

function habilitarEvento(num, id, plaza){
	if(xmlHttp){
		if(num != -1 && id != 0){
			var valor = document.getElementsByName("seleccionados[]")[num].checked;
			valor == true ? valor = 1 : valor = 0;
			cache.push('accion=habilitar_evento&id=' + id + '&valor=' + valor + '&plaza=' + plaza);
			try{
				if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0 && cache.length > 0){
					var cacheItem = cache.shift();
					xmlHttp.open("GET", serverScript + '?' + cacheItem, true);
					xmlHttp.onreadystatechange = function(){
						if(xmlHttp.readyState == 4){
							if(xmlHttp.status == 200){
								var respuesta = xmlHttp.responseText;
								//alert(respuesta);
								if(respuesta.indexOf("ERRNO") >= 0 || respuesta.indexOf("errno:") >= 0 || respuesta.indexOf("error") >= 0 || respuesta.length == 0)
									throw(respuesta.length == 0 ? "Error de servidor." : respuesta);
								
								if(respuesta == 'habilitado')
									alert('El evento ha sido habilitado');
								if(respuesta == 'deshabilitado')
									alert('El evento ha sido deshabilitado');
								//setTimeout("habilitarEvento()", 500);
							}
							else{
								if(mostrarErrores)
									alert(xmlHttp.statusText);
							}
						}
					}
					xmlHttp.send(null);
				}
			}
			catch(e){
				if(mostrarErrores)
					alert(e.toString());
			}
		}
	}
}

function eliminarPersonal(id, fila, tipo){
	if(confirm('żEsta seguro de eliminar al trabajador?')){
		if(xmlHttp){
			try{
				if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
					xmlHttp.open("GET", serverScript + '?accion=eliminar_personal&id=' + id + '&tipo=' + tipo, true);
					xmlHttp.onreadystatechange = function(){
						if(xmlHttp.readyState == 4){
							if(xmlHttp.status == 200){
								var respuesta = xmlHttp.responseText;
								//alert(respuesta);
								if(respuesta.indexOf("ERRNO") >= 0 || respuesta.indexOf("errno:") >= 0 || respuesta.indexOf("error") >= 0 || respuesta.length == 0)
									throw(respuesta.length == 0 ? "Error de servidor." : respuesta);
								
								if(respuesta == 'borrado'){
									fila++;
									$('tbody tr:nth-child(' + fila + ')').fadeOut('slow');
								}
							}
							else{
								if(mostrarErrores)
									alert(xmlHttp.statusText);
							}
						}
					}
					xmlHttp.send(null);
				}
			}
			catch(e){
				if(mostrarErrores)
					alert(e.toString());
			}
		}
	}
}