var validEmail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;

$(document).ready( function() {

	// Conversión email
	$("a").each( function() {
		this.innerHTML = this.innerHTML.replace("[at]", "@");
		if (this.href) this.href = this.href.replace("[at]", "@");
	});
	
	// Links auto-resaltados
	var loc = document.location.href.split(/[\?#]/).shift().replace(/\/$/, '');
	$("a").each(function() { if (this.href == loc) $(this).addClass("selected"); });
	$("#navMenu > ul > li:has(li a.selected) > a").addClass("selected");
	
	// Despliegue menu
	$("#navMenu > ul ul", this).hide();
	$("#navMenu > ul > li").hover( function() { $("ul", this).slideDown(100); }, function() { $("ul", this).slideUp(100); } );
	
	// Columnas
	$(".colSet").each( function() {
		var h = 0;
		$(".col", this).each( function() { h = Math.max(h, $(this).height() ) } );
		$(".col", this).height( h );
	} );
	
	/* Checkbox pago transferencia */
	$("#pagoTransferencia").each( function() {
	
		var check = $(this);
	
		var switchValue = function( e, read ) {
		
			if (e) e.preventDefault();
	
			var referencia = $("#f_referencia").val();
			var uniqueId = $("#f_uniqueId").val();
					
			$.ajax({
				type	: "post",
				url		: "/com/sw.transf.php",
				data	: "r="+referencia+"&k="+uniqueId+"&read="+(read?1:0),
				success	: function( data ) {
				
					if (data == "1") {
						check.attr('checked', 'checked');
					} else if (data == "0") {
						check.removeAttr('checked');
					} else {
						alert("Respuesta inesperada: "+data);
					}
				
				},
				error	: function( t, e ) {
					alert("Error: "+t+", "+e);
				}
			});
		
		}
		
		check.click( switchValue );
		switchValue( null, true );
	
	} );

});

function checkForm( form ) {

	$('.fieldError', form).removeClass('fieldError');
	
	$('input.required, select.required, textarea.required', form).each( function() {
		if (!this.value) $(this).addClass('fieldError');
	} );
	
	var em = $('input.email:eq(0)', form).val();
	$('input.email', form).each( function() {
		if (!this.value || this.value != em || !validEmail.test(em) ) $(this).addClass('fieldError');
	} );
	
	if ($('.fieldError', form).size() > 0) return true;
}

function initFormResumen() {

	var plantillaAutores = $('.plantillaAutores').html().replace(/^<!--|-->$/g, '');
  
	var contarPalabras = function() {
		var editor = tinyMCE.EditorManager.get('resumen');
		var text = $(editor.getBody().innerHTML).text();
			text = text.replace(/<\?.*\?>/,"").replace(/<!.*>/,"");
			text = text.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s{2,}/igm," ");
		var words = text.split(/\s+/);
		var totalwords = [];
		//for (var i in words) if ((new RegExp('[\w]+', 'i')).test( words[i] )) totalwords.push(words[i]);
		for (var i in words) if (words[i]!="") totalwords.push(words[i]);
		$('.palabrasrestantes').text( 'Restantes: '+(300-totalwords.length) );
		
		return totalwords.length;
	}

	var actualizarAutores = function() {
     
		var autores = parseInt($('select[name=otrosAutores]').val());
		var cant = $('.listaAutores .autor').size();
		var i;
		
		if (cant > autores) {
			for (i = autores; i < cant; i++) {
				$('.listaAutores .autor:last').remove();
			}
		} else if (cant < autores) {
			for (i = cant; i < autores; i++) {
				$('.listaAutores').append( plantillaAutores.replace(/%NUMERO%/g, i+2) );
			}
		}
		
		if (autores > 0) $('#formEnvioResumenes .adv').show();
		else $('#formEnvioResumenes .adv').hide();
   
	}
   
	var linkAutor = function() {	
		$('input[name=autor_1_'+this.name+']').val( $(this).val() );
	}
   
	var submit = function(e) {
		e.preventDefault();
		tinyMCE.triggerSave();
		
		if (checkForm(this)) {
			alert("Por favor, revisa los campos marcados y comprueba que se han introducido corréctamente.");
			document.location.hash = "";
			document.location.hash = "content";		
		} else if (contarPalabras() > 300) {
			alert("El resumen no puede sobrepasar las 300 palabras.");
			document.location.hash = "";
			document.location.hash = "fieldsetResumen";		
		} else {
			$(this).unbind("submit");
			this.submit();		
		}
	}

	htmledit = tinyMCE.init({
	  mode : 'textareas',
	  theme : 'advanced',
	  class_filter : 'tinymce',
      theme_advanced_toolbar_location : 'top',
	  theme_advanced_toolbar_align : 'left',
	  theme_advanced_buttons1: 'copy,paste,separator,undo,redo,separator,bold,italic,underline,separator,bullist,numlist,sup,sub,separator,charmap',
	  theme_advanced_buttons2: '',
	  theme_advanced_buttons3: '',
      plugins : "paste",
      paste_use_dialog : false,
      paste_auto_cleanup_on_paste : true,
      paste_convert_headers_to_strong : false,
      paste_strip_class_attributes : "all",
      paste_remove_spans : true,
      paste_remove_styles : true,	  
	  width: '770px'
   });  
   
   // Radios por defecto
   $('input[type=radio].default').each( function() {
		if ($('input[name='+this.name+']:checked').size() == 0) {
			$(this).attr("checked", "checked");
		}
   } );

   $('#datosAutor input, #datosAutor select').blur( linkAutor );
   $('#datosAutor input, #datosAutor select').each( linkAutor );
   
   $('select[name=otrosAutores]').change( actualizarAutores );
   actualizarAutores();
   
   $('#formEnvioResumenes').submit( submit );
   
   setInterval( contarPalabras, 500 );
   
}

function initFormInscripcion() {

	var submit = function(e) {
		e.preventDefault();
		
		if (checkForm(this)) {
			alert("Por favor, revisa los campos marcados y comprueba que se han introducido corréctamente.");
			document.location.hash = "";
			document.location.hash = "content";		
		} else {
			$(this).unbind("submit");
			this.submit();		
		}
	}

	$('#formInscripcion').submit( submit );

}
