function cambiaEstilos(capa){
	var li = $('#li_' + capa);
	var div = $('#div_' + capa);

	li.attr('class', li.hasClass('conHijos') ? 'conHijosDesplegable' : 'conHijos');

	var divClass = div.attr('class');

	if (divClass.lastIndexOf("Desplegada")>0)
	{
		divClass = divClass.replace("Desplegada", "Plegada");
	}else
	{
		divClass = divClass.replace("Plegada", "Desplegada");
	}
	div.attr('class', divClass);

}

function desplegar(capa) {
	$('#menu_'+capa).slideToggle(500, function() {
		id = $(this).attr('id');
		cambiaEstilos(id.substr(5,id.length));
	});
	return false;
}

function enviaFormulario() {
	$('#campos').val('');
	$('#campos').val("&" +$('#formulario').serialize());		
}

function activaValidacionForm() {
	var form = $('#formulario');
	if(form.length > 0) {
		form.submit( function() {
			var continua = true;
			var error = "";
			$('.wd_fError', $(this)).each( function() {
				$(this).removeClass('wd_fError');
			});
			
			// Valida campos obligatorios
			$('.wd_fObligatorio', $(this)).each( function() {
				var campo = $(this);
				if(campo.val()=="") {
					campo.addClass('wd_fError');
					error = error + "El campo " + campo.attr('title') + " es obligatorio.\n";
					continua = false;
				}
			});
			
			// Valida NIFs/NIEs/CIFs
			$('.wd_fDNI', $(this)).each( function() {
				var campo = $(this);
				if(campo.val()!="" && !valida_nif_cif_nie(campo.val())) {
					campo.addClass('wd_fError');
					error = error + "El campo " + campo.attr('title') + " no contiene un identificador v\u00E1lido.\n";
					continua = false;
				}
			});
			
			if(!continua) alert(error);
			return continua;
		});
		$('.wd_fFecha').datepicker();
	}
}

function slideSwitch(idCapa) {
	if(idCapa=="") idCapa = 'slide-images'; // Para c\u00F3digo existente antes de ser configurable
    var $active = $('#' + idCapa + ' li.active');

    if ( $active.length == 0 ) $active = $('#' + idCapa + ' li:last');

    var $next =  $active.next().length ? $active.next()
        : $('#' + idCapa + ' li:first');

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

// Ampliaci\u00F3n de galerias laterales
function activaGaleriaLateral() {
	if($('#bloqueDer #ampliacionGaleria').length > 0) {
		$('#galeria a').live('hover', function() {
		    var parseo=/(.*nsf).*0\/(.*)\/\$/i.exec($(this).attr('href'));
		    var ruta=parseo[1];
		    var unid=parseo[2];
		   $('#ampliacionGaleria').load(ruta + '/vGaleriaDetalleLateral/' + unid)
		})
	}
}

//Retorna: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF error, -2 = CIF error, -3 = NIE error, 0 = ??? error
//C\u00F3digo original: http://compartecodigo.com/javascript/validar-nif-cif-nie-segun-ley-vigente-31.html
function valida_nif_cif_nie(a) 
{
	var temp=a.toUpperCase();
	var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
 
	if (temp!==''){
		//si no tiene un formato valido devuelve error
		if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			return 0;
		}
 
		//comprobacion de NIFs estandar
		if (/^[0-9]{8}[A-Z]{1}$/.test(temp))
		{
			posicion = a.substring(8,0) % 23;
			letra = cadenadni.charAt(posicion);
			var letradni=temp.charAt(8);
			if (letra == letradni)
			{
			   	return 1;
			}
			else
			{
				return -1;
			}
		}
 
		//algoritmo para comprobacion de codigos tipo CIF
		suma = parseInt(a[2])+parseInt(a[4])+parseInt(a[6]);
		for (i = 1; i < 8; i += 2)
		{
			temp1 = 2 * parseInt(a[i]);
			temp1 += '';
			temp1 = temp1.substring(0,1);
			temp2 = 2 * parseInt(a[i]);
			temp2 += '';
			temp2 = temp2.substring(1,2);
			if (temp2 == '')
			{
				temp2 = '0';
			}
 
			suma += (parseInt(temp1) + parseInt(temp2));
		}
		suma += '';
		n = 10 - parseInt(suma.substring(suma.length-1, suma.length));
 
		//comprobacion de NIFs especiales (se calculan como CIFs)
		if (/^[KLM]{1}/.test(temp))
		{
			if (a[8] == String.fromCharCode(64 + n))
			{
				return 1;
			}
			else
			{
				return -1;
			}
		}
 
		//comprobacion de CIFs
		if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp))
		{
			temp = n + '';
			if (a[8] == String.fromCharCode(64 + n) || a[8] == parseInt(temp.substring(temp.length-1, temp.length)))
			{
				return 2;
			}
			else
			{
				return -2;
			}
		}
 
		//comprobacion de NIEs
		//T
		if (/^[T]{1}/.test(temp))
		{
			if (a[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
			{
				return 3;
			}
			else
			{
				return -3;
			}
		}
 
		//XYZ
		if (/^[XYZ]{1}/.test(temp))
		{
			pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
			if (a[8] == cadenadni.substring(pos, pos + 1))
			{
				return 3;
			}
			else
			{
				return -3;
			}
		}
	}
 
	return 0;
}

function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman

    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
 
    return sa ? s : s[0];
}


$(document).ready( function() {
	// Formularios
	activaValidacionForm();
	// Galer\u00EDa lateral
	activaGaleriaLateral();
	// Slideshow en portada
	if($('#slide-images').length>0) setInterval( "slideSwitch('')", 4000 );
	// Rotor de noticias
	if($('#wd-rotor').length>0) {
		slideSwitch('wd-rotor');
		setInterval( "slideSwitch('wd-rotor')", 4000 )
	};
})
