/*
* Lo q hace esta funcion es mostrar un mensaje para confirmar 
* si se quiere realizar el borrado de un campo
*/
function confirmacion(msg)
{ 
	if (confirm('¿Está seguro que quieres borrar ' + msg + ' ?')) 
		return true; 
	else 
		return false;
} 

var focusField = null;

// This function is used by the login screen to validate user/pass
// are entered. 
function validateRequired(form, fields) {                                    
    	

	oRequired = new required();                                                                         
	
	var cont_textareas = 0;
	
    for (x in oRequired) {                                                                                  		
		
        if ((form[oRequired[x][0]].type == 'text' || 
        	//form[oRequired[x][0]].type == 'textarea' || 
        	form[oRequired[x][0]].type == 'select-one' ||        	 
        	form[oRequired[x][0]].type == 'radio' || 
        	form[oRequired[x][0]].type == 'password' || 
        	(form[oRequired[x][0]].type == 'select-multiple' && (form[oRequired[x][0]].options.length == 0))) && 
        	form[oRequired[x][0]].value == '') 
        	{
				i = fields.length;
				
				if (i == 0)
					focusField = form[oRequired[x][0]];
				
				
				fields[i++] = oRequired[x][1];
        	}        	

			if (form[oRequired[x][0]].type == 'textarea' )
			{
				var editor1 = tinyMCE.getInstanceById("mce_editor_" + cont_textareas);
				var cadena  = editor1.getBody().innerHTML;
				//alert(cadena);
				cadena = cadena.replace("<br>", "")
				if (cadena.length == 0)
					fields[i++] = oRequired[x][1];
				cont_textareas++;
			}	
		
     }		
	 
	 
			   
			                                                                                
}

// This function is used by the login screen to validate user/pass
// are entered. 

function validateReglas(form, fields) {                                    

    oReglas = new reglas_validacion_form_envio_articulo();                                                                         
	
	NOMBRE_REGLA = 0;
	VALOR_NECESARIO = 1;
	NOMBRE_CAMPO = 2;
	MENSAJE_CAMPO = 3;
	/*
		campo 0 = nombre de la regla
		campo 1 = valor necesario para comprobar
		campo 2 = nombre del campo
		campo 3 = mensaje
	*/
    
	for (x in oReglas) 
    { 
		i = fields.length;
	
		if (i == 0)
			focusField = form[oReglas[x][2]];
				
		switch (oReglas[x][NOMBRE_REGLA]) {
		
			case 'minimo':	
							minimo = oReglas[x][VALOR_NECESARIO];
							
							if (form[oReglas[x][2]].options.length < minimo)
          						fields[i++] = oReglas[x][3];
							
							break;
							
			case 'maximo':	
							maximo = oReglas[x][VALOR_NECESARIO];
							
							if (form[oReglas[x][2]].options.length > maximo)
          						fields[i++] = oReglas[x][3];
							
							break;
							
			case 'maximo_palabras': 
																																					
									var maximo_palabras = parseInt(oReglas[x][VALOR_NECESARIO]);
									
									//Esto no se porque hay q hacerlo para que funcione
									for (j=0; j< oReglas[x].length; j++)
									{
										if (j == 3)
											msg = oReglas[x][j];
										//alert("j " + j + " = " + oReglas[x][j]);
									}
									
									//alert("maximo_palabras = " + maximo_palabras);
																	
									//contamos palabras
									var num_palabras_text_area = parseInt(getNumeroPalabras_textarea(form[oReglas[x][2]]));
									
									//alert("num_palabras_text_area = " + num_palabras_text_area);
																											
									if (num_palabras_text_area > maximo_palabras)
           							{
										//alert("AHORA!!");
										fields[i++] =  msg;																			
									}											
									break;
									
		}
		       	
    }                                                                                                                                                                                                         
    
}



function validateForm(form) { 
	var bValid = true;
	
	var i = 0;                                                                                          
	var fields = new Array(); 
		
	validateRequired(form, fields); 
	validateReglas(form, fields);                                                              
	
	if (fields.length > 0) {    
		focusField.focus();
		alert("ERRORES COMETIDOS\n-------------------------------------------------------------\n" + fields.join('\n'));                                                                      	   
		bValid = false;		
    }                                                                                                   
           
		                                                                                               
   return bValid;
	
   //return validateRequired(form); 
}

function getNumeroPalabras_textarea(text_area) {
	var area_content = text_area.value;
	area_content = area_content.split(" ");
		
	
	if (area_content == "")
		total = 0;
	else
	{
		total = area_content.length;
		
		for (x in area_content)
		{
			if (area_content[x].length == " ")
				total--;
		}
		if (total < 0)
			total=0;

	}
	return (total);
}

// Show the document's title on the status bar
window.defaultStatus=document.title; 


/*
* Funciones para mostrar u ocultar divs
*/

function expandCollapse() {
	for (var i=0; i<expandCollapse.arguments.length; i++) {
		var element = document.getElementById(expandCollapse.arguments[i]);
		element.style.display = (element.style.display == "none") ? "block" : "none";
	}
}



/*
* Funciones para mostrar u ocultar divs
*/

function showTocToggle(show,hide) {
	if(document.getElementById) {
		document.writeln('<span class=\'toctoggle\'>[<a href="javascript:toggleToc()" class="internal">' +
		'<span id="showlink" style="display:none;">' + show + '</span>' +
		'<span id="hidelink">' + hide + '</span>'
		+ '</a>]</span>');
	}
}

/*
* Funciones para mostrar u ocultar divs
*/
function toggleToc() {
	var toc = document.getElementById('tocinside');
	var showlink=document.getElementById('showlink');
	var hidelink=document.getElementById('hidelink');
	if(toc.style.display == 'none') {
		toc.style.display = tocWas;
		hidelink.style.display='';
		showlink.style.display='none';

	} else {
		tocWas = toc.style.display;
		toc.style.display = 'none';
		hidelink.style.display='none';
		showlink.style.display='';

	}
}
/*
* FUnciones para aï¿½adir palabras a un listado
*/
function addPalabra(input, select, input_hidden) {

	if (input.value != "")
	{
		select[select.length] = new Option(input.value, select.length);			

		if (input_hidden.value.length == 0)
		{
			input_hidden.value = input.value; 
		}
		else
		{
			input_hidden.value += (", " +  input.value); 
		}
				
	}	
		
	input.value="";
	input.focus();
}

function deletePalabraClave(select, input_hidden) {
	if (select.selectedIndex >= 0) {
		select.options[select.selectedIndex]=null;
		select.selectedIndex=0;

		if (select.options.length > 0)
		{
			input_hidden.value = select.options[0].text; 
			
			for(i=1;i<select.options.length; i++) 
				input_hidden.value += (", " + select.options[i].text);
		}
		else
			input_hidden.value = ""; 
	}
}
  
/*
* Funciones para aï¿½adir autores a un listado
*/
function addAutor(input, select, input_hidden) {

	if (input.value != "")
	{
		select[select.length] = new Option(input.value, select.length);			

		if (input_hidden.value.length == 0)
		{
			input_hidden.value = input.value; 
		}
		else
		{
			input_hidden.value += (":" +  input.value); 
		}
				
	}	
		
	input.value="";
	input.focus();
}

function deleteAutor(select, input_hidden) {
	if (select.selectedIndex >= 0) {
		select.options[select.selectedIndex]=null;
		select.selectedIndex=0;

		if (select.options.length > 0)
		{
			input_hidden.value = select.options[0].text; 
			
			for(i=1;i<select.options.length; i++) 
				input_hidden.value += (":" + select.options[i].text);
		}
		else
			input_hidden.value = ""; 
	}
} 

//Funcion que devuelve el index de un valor seleccionado
function getIndexSelect(select, valor_seleccionado)
{
	var index = 0;

	for (i=0; i<select.options.length;i++)
	{
		//alert(select.options[i].index + " " + select.options[i].value + " " + select.options[i].text); //selectedIndex 
				
		if (select.options[i].value ==  valor_seleccionado)
		{
			//alert("IGUALES");
			index  = select.options[i].index;
		}
	}
	return index;
	

}  

function confirmacion_submit()
{ 

	if (confirm('¿Está seguro que todos los datos son correctos?')) 
			return true; 		
		
	return false;
}

function submit_form(name_form) {
	var form_submit = false;	

	if (name_form.file.value != "")
		form_submit = true; 
	else			
		alert("ERROR: Debes introducir un fichero.");

	return (form_submit);
}

function SubmitForRemove(name_form) {
	document.name_form.submit();
	
}
/********SCRIPTS RELACIONADOS CON LAS NOTICIAS ***********************************/
function borrar_noticia(id , title)
{
	if (confirm('¿Está seguro que quiere borrar la noticia?')) 
	{		
		document.form_delete.id.value = id
		document.form_delete.submit();	
	}
}

function updateCampoProgramada()
{	
	if (document.form_news.programada.value == 1)
		document.form_news.programada.value = 0;
	else
		document.form_news.programada.value = 1;
			
	expandCollapse('on_div_calendario', 'off_div_calendario');
}

function submit_form_news()
{
    var resp = true;
	
    with (document.form_news)
    {
	if (programada.value == 1)
	   resp = compfechas(pDesde, pHasta);	
		
    }
	
    return resp;	
}

function compfechas(fecha_inicio,fecha_fin)
{
	var fec1 = fecha_inicio.value;
	var fec2 = fecha_fin.value;
		
	if ((fec1 == "") ||  (fec2 == ""))
	{
		alert("Formato de fecha incorrecta");
		return false;
	}
	
	if (!mayor(fec1, fec2)) 
	{
		alert("La fecha de finalización debe ser mayor que la fecha de inicio");		
		//myfecha.focus();
		return false;
	}
	else
		return true;

} 

function mayor(fecha, fecha2)
{
	var xMes=fecha.substring(3, 5)*1;
	var xDia=fecha.substring(0, 2*1);
	var xAnio=fecha.substring(6,10)*1;
	var yMes=fecha2.substring(3, 5)*1;
	var yDia=fecha2.substring(0, 2)*1;
	var yAnio=fecha2.substring(6,10)*1;

	var resp = true;

	if (xAnio > yAnio)
	{
			//alert("xAnio > yAnio");
			resp = false;
	}
	else
		if (xAnio == yAnio)
		{
			if (xMes > yMes)
			{
				//alert("xMes > yMes");
				resp = false;
			}
			else
			{ 
				if (xMes == yMes)
				{				
					if (xDia > yDia)
					{
						//alert("xDia > yDia");
						resp = false;
					}
				}
			}			
		}
		
	if (resp)
	{
		with (document.form_news)
		{
			fecha_inicio.value = xAnio + "-" + xMes + "-" + xDia;
			fecha_fin.value = yAnio + "-" + yMes + "-" + yDia;
		}	
	}	
	
	return resp;
} 
/***********************************************************************/
/*
* Funciones para mostrar una pestaï¿½a
*/
function expandirPestanya(nombre_pestanya) 
{	
    if (pestanya_actual != nombre_pestanya)
    {
	//1.- Ocultar la pestanya_actual);
	var element = document.getElementById(pestanya_actual);
	element.style.display =  "none";

	var input_foco = document.getElementById("field_title");
	input_foco.focus();

	//1b.- Quitar la clase del enlace
	var clase_element = document.getElementById("a_" + pestanya_actual);
	clase_element.className =  "";
		
	//2.- Activamos la nueva pestanya);
	element = document.getElementById(nombre_pestanya);
	element.style.display =  "block";
	
	//3.- Actualizamos la pestaï¿½a actual;
	pestanya_actual = nombre_pestanya;
	
	clase_element = document.getElementById("a_" + pestanya_actual);
	clase_element.className =  "active";
    }	
}

function inicializarEditor()
{
    tinyMCE.init({
	mode : "textareas",
	theme : "advanced",
	plugins :"paste", /*"safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",		*/
	theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,|,formatselect,fontselect,fontsizeselect",
	//theme_advanced_buttons2 : "",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,outdent,indent,|,undo,redo,link,unlink,removeformat,",
	theme_advanced_buttons3 : "",
	//theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_path_location : "bottom",
	extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]"
    });	
}

/*function getNombreApellidos(ApellidosNombre)
{

	<#list ApellidosNombre?split(",") as nombre >						
		<#if !(nombre_has_next)>
			<#assign nombreFinal = nombre + " " + apellidos />
		</#if>
		<#assign apellidos = nombre />
	</#list>	
	
	return ${nombreFinal};

}*/
