var upload_number = 2;  // para el upload dinamico 
var pos = 0;            // para el titulo rotativo
var tarea = 0;




function addFileInput() {
	 var d = document.createElement("div");
	 d.setAttribute("id", "div"+upload_number);
	 
	 var file = document.createElement("input");
	 file.setAttribute("type", "file");
	 file.setAttribute("name", "attach"+upload_number);
	 
	 var a = document.createElement('a');
	 a.appendChild(document.createTextNode(' eliminar'));
	  a.setAttribute('href', "javascript:deleteFileInput('div" +upload_number +"')");

	 d.appendChild(file);
	 d.appendChild(a);
	 document.getElementById("moreUploads").appendChild(d);
	 upload_number++;
}

function deleteFileInput(divnum) {
	var d = document.getElementById("moreUploads");
	var div = document.getElementById(divnum);
	d.removeChild(div);
}

function setBlock() {
	 document.getElementById('moreLink').style.display = 'block';
}



function abrir_adjuntar()
{
	window.open ("adjuntar.php","vndadjunto","toolbar=NO, menubar=NO, resizable=YES, height=300, width=600 ");


}

function abrir (pagina)
{
	window.open (pagina,"Modificar usuario","toolbar=NO, menubar=NO, resizable=YES, height=300, width=600 ");
}



function ControlPassword ( id ) {

	o1 = document.getElementById('password1');
	o2 = document.getElementById('password2');

	if ( id == 'p1' ) {
		o1.style.visibility = "hidden"; 
		o1.disabled = true;

		o2.style.visibility = "visible"; 
		o2.disabled = false;

		o1.blur();
		o2.focus();

		o2.style.color = "#000000";
		o2.style.fontStyle = "normal";
	}
	
	if ( (id == 'p2') && (o2.value == "") ) {
		o1.style.visibility = "visible"; 
		o1.disabled = false;

		o2.style.visibility = "hidden"; 
		o2.disabled = true;

		o1.blur();
		o2.focus();
	}
}


function Rellenar ( obj, texto, texto_deberia_tener ) { // onblur
	//obj.value = trim(obj.value);
	
	if ( (obj.value == "") ) {
		obj.style.color = "#D32020";
		obj.style.fontStyle = "italic";
		obj.value = texto;	
	} 
	
}


function Vaciar ( obj, texto, texto_deberia_tener ) {  // onfocus
	//obj.value = trim(obj.value);
	
	if ( obj.value == texto ) {
		obj.style.color = "#000000";
		obj.style.fontStyle = "normal";
		obj.value = "";
	} 
}

function trim ( str ) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}


function desplazar_titulo( )
{
	var msg = " mensajes sin leer";
	var spacer = "... ";

	///if (!t) x=document.title;
	
	document.title = msg.substring(pos, msg.length) + spacer + msg.substring(0, pos);
	pos++;
	if (pos > msg.length) pos=0;
	
}



function On_CambiarFecha() {
	var Year  = document.when.year.selectedIndex.value;
	var Month = document.when.month.selectedIndex.value;

	ajax_mover_calendario ( Month, Year );
}



function iluminar_fila_mensajes ( id, color ) 
{
	// de 1 a 4; todas la columnas
	for ( i=1; i<5; i++ ) { 
		a = 'td_' + i + '_' + id;
		
		e = document.getElementById(a);
		e.style.backgroundColor = color;
	}
}



function guardar_mensajes_seleccionados ( )
{                                         
	cuantos = ajax_contar_usuarios_marcados('mensajes');
	
	if ( cuantos > 0 )
	{
		if ( cuantos == 1 ) 
		{
			msg = "¿Deseas guardar este mensaje?" 
		} 
		else
		{
			msg = "¿Deseas guardar estos mensajes?" 
		}
		
		ret = confirm ( msg );
		if ( ret ) ajax_mostrar_mensajes_sincrono('refrescar_tras_guardar');
	} 
	else
	{
		alert ( "No hay ningún mensaje seleccionado." );
	}
}



function borrar_mensajes_seleccionados ( )
{
	cuantos = ajax_contar_usuarios_marcados('mensajes');

	if ( cuantos >  0 )
	{
		if ( cuantos == 1 ) 
		{
			msg = "¿Deseas borrar este mensaje?" 
		} 
		else
		{
			msg = "¿Deseas borrar estos mensajes?" 
		}
		
		ret = confirm ( msg );                          
		if ( ret ) ajax_mostrar_mensajes_sincrono('refrescar_tras_eliminar');
	} 
	else
	{
		alert ( "No hay ningún mensaje seleccionado." );
	}
}

function borrar_usuarios_seleccionados ()
{
	cuantos = ajax_contar_usuarios_marcados ('usuarios');
	if (cuantos > 0){
		if (cuantos == 1){
			msg = "¿Deseas eliminar este usuario?" 
		}else{
			msg = "¿Deseas eliminar estos usuarios?" 
		}
		ret = confirm ( msg );                          
		if (ret){
			ajax_borrar_usuarios();
		}
	}else{
		alert ( "No hay ningún usuario seleccionado." );
	} 
}


function borrar_grupos_seleccionados ()
{
	cuantos = ajax_contar_usuarios_marcados ('usuarios'); //van a ser grupos
	if (cuantos > 0){
		if (cuantos == 1){
			msg = "¿Deseas eliminar este grupo?" 
		}else{
			msg = "¿Deseas eliminar estos grupos?" 
		}
		ret = confirm ( msg );                          
		if (ret){
			ajax_borrar_grupos();
		}
	}else{
		alert ( "No hay ningún grupo seleccionado." );
	} 
}

function borrar_empresas_seleccionadas ()
{
	cuantos = ajax_contar_usuarios_marcados ('usuarios'); //van a ser grupos
	if (cuantos > 0){
		if (cuantos == 1){
			msg = "¿Deseas eliminar esta empresa?" 
		}else{
			msg = "¿Deseas eliminar estas empresas?" 
		}
		ret = confirm ( msg );                          
		if (ret){
			ajax_borrar_empresas();
		}
	}else{
		alert ( "No hay ninguna empresa seleccionada." );
	}    
}

function borrar_tareas()
{
	cuantos = ajax_contar_usuarios_marcados ('tareas');
	if (cuantos > 0){
		if (cuantos == 1){
			msg = "¿Deseas eliminar esta tarea?" 
		}else{
			msg = "¿Deseas eliminar estas tareas?" 
		}
		ret = confirm ( msg );                          
		if (ret){
			ajax_borrar_tareas();
		}
	}else{
		alert ( "No hay ninguna tarea seleccionada." );
	}
}


function comprobar_mensaje ()
{
	var res = true;
	
	/* Comprobamos si hay usuarios marcados */
	n_usuarios = ajax_contar_usuarios_marcados('usuarios');
	if (n_usuarios == 0){
		/* No hay usuarios marcados */
		alert ("Tienes que marcar algun destinatario del mensaje");
		res = false
	}
	
	var v_asunto = document.envio_mens.asunto.value;
	if (v_asunto == "asunto" && res){
		/* No tiene asunto */
		res = confirm ("¿Estas seguro de mandar el mensaje sin asunto?");
	}
	
	var v_tipo = document.envio_mens.tipo_envio.value;
	if (v_tipo == "" && res){
		/* No tiene tipo de envio */
		alert ("Tienes que seleccionar el tipo de envio");
		res = false;
	}
	 
	/* Mandamos el formulario o no */
	if (res == true){
		// Ponemos la barra de progreso
		bar.showBar();
		document.envio_mens.submit();
	}
}

function guardar_borrador()
{
	 mensaje = tinyMCE.getContent();
	 asunto = document.envio_mens.asunto.value;
	 if (asunto == 'asunto'){
		  asunto = "";
	 }
	 // Guardamos el mensaje en borrador
	 ret = ajax_guardar_borrador (asunto, mensaje);
	 alert ("Mensaje guardado correctamente en Borrador.\nNota: Los adjuntos no serán guardados.");
}


function comprobar_admin_usuarios ()
{       
	 var res = true;
	 // Comprobamos los datos introducidos
	 if (document.form_admin.nombre_box.value == ""){
		  res = false;
		  msg = "Error: Introducir nombre usuario";
	 }
	 if (document.form_admin.pass_box.value == "" && document.form_admin.id_box.value == ""){
		  res = false;
		  msg = "Error: Introducir contraseña del usuario";
	 }
	 if (document.form_admin.pass_box.value != document.form_admin.pass2_box.value){
		  res = false;
		  msg = "Error en repeticion de contraseña";
	 }
    
    if ( !res ) alert ( msg );
    
    return res;
}


function comprobar_admin_grupos ()
{
	 if (document.form_admin_grupos.nombre_box.value == ""){
		  alert ("Error: Introducir el nombre del grupo");
	 }
	 
	 document.form_admin_grupos.submit ();
}

function comprobar_admin_empresa ()
{
	 if (document.form_admin_empresas.nombre_box.value == ""){
		  alert ("Error: Introducir el nombre de la empresa");
	 }
	 document.form_admin_empresas.submit ();
}

/*function anadir_tarea (id)
{
	 document.calendario.submit();
}*/

function mostrar_tarea (indice)
{
	 // Si ya tiene la fila textarea, no poner mas
	 if (!document.getElementById ("text"+indice)){
		  
		  if (tarea > 0){
				tarea--;
				document.calendario.submit();
		  }
		  // Si ya tiene texto, insertarlo en textarea
		  div_t = document.getElementById ("div_text_"+indice);
		  if (div_t){
				value = div_t.innerHTML; 
				value = str_replace ('<br>', ' ', value);
				div_t.innerHTML = "";
		  }else{
				value = "";
		  }
		  // Sino crearlo
		  var nom = "td_2_"+indice;
		  var elem = document.getElementById (nom);
		  
		  var textarea = document.createElement("textarea");
		  textarea.setAttribute ("id", "text"+indice);
		  textarea.setAttribute ("name", "text"+indice);
		  textarea.setAttribute ("cols", 120);
		  textarea.setAttribute ("rows", 5);  
		  textarea.innerHTML = value;                        
		  
		  elem.appendChild(textarea);
		  tarea++;
	 }
}

function abrir_perfil (id_usuario){
	 window.open ("perfil.php?x="+id_usuario, "perfil", "width=500 height=600" );
}

function cambiar_perfil ( id_usr_emp, referencia ) {
	 //borrar_session_cp();
	 location.href = "funciones.php?x=cambiar_perfil&y="+id_usr_emp+"&referencia="+referencia;
} 

function borrar_relacion (id_relacion){
	 location.href = "funciones.php?x=borrar_relacion&y="+id_relacion;    
}

function registrar(){
	 //alert ("Tu registro se ha mandado correctamente");
	 window.open ("registro.php", "registro", "width=500 height=600" );
}

function aceptar_registro (){
	 n_empresa = document.form_registro.empresa_box.value;
	 email = document.form_registro.email_box.value;
	 var res = true;
	 
	 // Comprobamos valores 
	 if (n_empresa == ""){
		  alert ("Error: debes de escribir el nombre de la empresa a registrar");
		  res = false;
	 }
	 if (email == ""){
		  alert ("Error: debes de escribir el email donde mandaremos la confirmacion del registro");
		  res = false;
	 }
	 
	 if (res == true){
		  //alert ("Su registro se ha mandado correctamente");
		  document.form_registro.submit();
	 }else{
		  location.href = "registro.php";
	 }
}

function aceptar_registro_u (){
	 n_usuario = document.form_registro.n_usuario_box.value;
	 t_usuario = document.form_registro.t_usuario_box.value;
	 e_usuario = document.form_registro.e_usuario_box.value;
	 r_empresa = document.form_registro.r_empresa.value;
	 //alert (n_usuario);alert (t_usuario);alert (e_usuario);alert (r_empresa);
	 
	 if (n_usuario == "" || t_usuario == "" || e_usuario == ""){
		  alert ("Error: debes de rellenar todos los campos del usuario");
		  location.href = "registro.php";
	 }else{
		  document.form_registro.submit();
	 }
}

function cpCrearTarea(){
	 // Iluminar la pestaña de crearTarea
	 
	 pestCrear = document.getElementById("c_td");
	 pestCrear.className = "menu_acciones_marcada";

	 pestListar = document.getElementById("l_td");
	 pestListar.className = "menu_acciones";

	 // Cambiar el tipo de letra de las pestañas
	 pestCrear_a = document.getElementById("c_a");
	 pestCrear_a.className = "opcion_acciones_marcada";
	 pestListar_a = document.getElementById("l_a");
	 pestListar_a.className = "opcion_acciones";
		  
	 //document.getElementById("cp").src="http://cp.grupoevolucion.es/index.php?seccion=tarea&subseccion=crear";
	 document.getElementById("cp").src="cp/index.php?seccion=tarea&subseccion=crear";
	 // VACIAMOS EL MENU ELEMENTOS
}


function cpListarTareas()
{
	 // Iluminar la pestaña de crearTarea
	 
	 pestCrear = document.getElementById("c_td");
	 pestCrear.className = "menu_acciones";

	 pestListar = document.getElementById("l_td");
	 pestListar.className = "menu_acciones_marcada";

	 // Cambiar el tipo de letra de las pestañas
	 pestCrear_a = document.getElementById("c_a");
	 pestCrear_a.className = "opcion_acciones";
	 pestListar_a = document.getElementById("l_a");
	 pestListar_a.className = "opcion_acciones_marcada";
	 
	 //document.getElementById("cp").src="http://cp.grupoevolucion.es/index.php?seccion=tarea&subseccion=listar";
	 document.getElementById("cp").src="cp/index.php?seccion=tarea&subseccion=listar";
	 //document.getElementById("categoriasCp").src="http://cp.grupoevolucion.es/html/listarCategorias.php";
	 document.getElementById("categoriasCp").src="cp/html/listarCategorias.php";	 
}


function logout(){
	 //document.getElementById("cp").src = "http://cp.grupoevolucion.es/index.php?seccion=usuario&subseccion=salir";
	 document.open("logout.php");
}
  
function borrar_session_cp()
{
	document.getElementById("cp").src="cp/ajax/borrar_session.php";
}
